Categories
JSON

Json and objects

One of my goals in my current project, making a text based adventure game, is to create a method of saving the state of the game and loading it later. Last week I went in depth on a method of saving dictionaries but that falls a little short when it comes to a larger project. What would be really useful is the ability to store the attributes of a given object and retrieve them later. Then ideally if I created a new instance of an object when the game opens, say representing a room, I could simply write the saved attributes over the ones it is initiated with. That way if a player “dropped” and item in the room it would be preserved in one of the attributes. This could also be used to save states of features in the room, or other changes that the player makes. Additionally it allows the room class that the object is created from to inherit all of the methods that might be tied to it, eg. get exits, get description, that kind of thing. Here’s what I came up with.

same as last time remember to import json before following along.

Basic Setup

We will need an example class to work with, so we will initialize a basic car class and give it a few attributes as well as a method. Honk probably would have been a better method but I’ve ben watching too much Knight Rider lately so our car can talk.

Its always good to throw in a couple test prints just to make sure the basic stuff is working. Your current output should look something like this

Boom we have a talking Honda city. Its no Pontiac Firebird but lets try to save it anyway.

Save the attributes

While JSON is an incredible tool it seems that it mostly likes saving dictionaries. There are more complicated ways to store a whole object but I found this method to suit my purposes the best. We are going to save our attributes as a dictionary so we can restore them to a new instance of the object at a later point. We can to this with a method very similar to the dictionary saving I covered in my last post.

The first think we need to do is convert to JSON format so we use json.dumps() to dump a dictionary of our objects attributes. Very handy. Throw in a test print to makes sure the string looks right and then make a new to a JSON file using the same with open() command I introduced in my last post. Finally we can use json.dump() to send the formatted string to the file that we just created. As with last week your output shoudnlt change much but you will notice a new JSON file named attributes_save in the same folder as your main python folder.

Now that we have a dictionary of our object attributes saved pretend we are starting a new instance of our game. We ultimately want to make a new car with the same attributes as our first so lets start by grabbing them from the saved JSON dictionary.

We can use with open() and the ‘r’ attribute to read the JSON file. Then we save the new data by running json.load() with the file alias and assigning it to the varible “data” on line 39. We then use json.loads() to make it a python dictionary. This pretty much the same process we used to get JSON data in the last post. This time however, after we confirm that the data is good with a couple test prints we are going to do something different.

Make a new object with the old attributes

This bit is quick but essential, don’t blink or you’ll miss it.

Ok so what happend there.

Lets start with the first bit, we created a new car object. When we do that it should have the initial attributes all cars start with, but those are effectively junk values when we want our cool Honda City back. When we make the call to make a Car object we pass in **and the dictionary of data that we retrieved as the attribute values for our new car. Thus we have created an object that is essentially exactly the same as the one we saved. Since new_car was created as a Car object it also has access to all of the same methods as the original. The only draw back to this approach is that you have to know ahead of time what the attribute fields of your object are but it works for the purposes of saving.

you should at this point be able to get the old values from the new_car object! Well done!

Here’s a link to my get hub with the complete code for reference.

https://github.com/samuelh223/Json_objects_dictionary/blob/main/main

Categories
JSON

Saving a dictionary with JSON

In my current project I am at some point going to need to save data to a file and load the data back in the next time they are going to use the program. With Python there are a few ways to do this but the most common seems to be using JSON. The problem I found in much of the existing material available after a quick google is that an individual tutorial might tell you a piece of the information you need but many of them gloss over crucial steps in order to tell you five different ways to turn your data into a json dictionary. Great information but less that practical. I’m going to show you a way that works start to finish. Is it the best? Well it works so lets start there.

Remember to import json before you start coding.

Moving a dictionary into a JSON file

In order to save anything into a JSON file you need to covert it into the proper format. This is where json.dumps() function comes in. You can see below that I declared and example dictionary and then converted the dictionary by passing it to json.dumps()

If you print it out at this point you will see that the file has been changed into the JSON format.

The next step is to take this formatted information and save it to a JSON file. To do this we can use with open(). When we pass the function these parameters with open will either make or open a file called dictionary_save.json note that this can be whatever file name as long as it ends in .json. We will also pass the “w” argument because we are writing to the file. Note that when we refer to the file in this section of the code have designated it thisdict_file. Very handy we want to do anything with that file we just went through all the trouble of creating. The very last thing here is to use json.dump() and pass it the formatted data we saved to dict_1 above and the file we want to send it to. Good thing we have that reference to our file.

If you run the program right now you aren’t going to see much difference. but if you open where ever your folder for the program it or you can see it in your IDE you might notice an addition.

Its the file we just created! If you open it you can see that your data is stored in there.

This is how it looks in the python editor.

Moving a dictionary out of a JSON file

Cool now you information is saved now you need to know how to access it when you need it. This section has two parts, you have to retrieve the json data and then turn it back into something you can use.

You can use with open() and pass it the file name you are trying to access and the ‘r’ argument and it will let you read the file. We also tell it we are going to be referring to the file as thisdict_save for this section of code.

We also have a chance to use another JSON function here, json.load(). This will grab the data from our file and save it to our cleverly named variable.

If you print the data variable the output should look something like this

In other words exactly the same thing we sent in.

I have to say that I am a little put out that some guides decided to stop here in their explanations. After all you got the formatted information back but you can’t do anything with it. Useless.

That’s where this little one liner comes in.

json.loads() turns JSON formatted data back into a dictionary that you can reference normally. There is a subtle difference in the prints but if you have double quotes around you dictionary when you print, it is likely still in JSON format as in the first line below.

Single quotes on your dictionary mean that you have it back to a workable Python format.

CONGRADULATONS!!

You just stored a dictionary in a JSON file and got it back to a working Python dictionary. Small victories add up to something larger.

Check out my GitHub for the full code I used for this explanation.

https://github.com/samuelh223/json_dictionary_convert