Python challenge: Handling json files
This blog post describes how to read and write json files in python 3.
Reading json files
In this example, the python script will read product information from an existing json file.
The content of products.json is as follows:
In general we have two alternatives:
- we read only the raw data and get the result as a dictionary.
- we read the raw data and parse them into objects, so the result will be a listof objects.
The following code reads the json file and returns a dictionary. If the file does not exist, a FileNotFoundError will be thrown that has to be handled by the caller of this function.
Nothing more than that. However, the result is probably of not much value as it is just a (potentially large) dictionary.
The next step is to parse that dictionary into something more usable. In this concrete example, a list of products sounds reasonable.
The following is the definition of the Product class:
Next, the content of the json file needs to be handled in a way that a list of products is returned.
Writing json files
Again, not much work is required.
The function takes two arguments: The name of the json file and a list of products.
When the above functions is called, the following error occurs:
So obviously something is missing before data can be written to a json file. As the error message suggests, the objects in the list of products are not serializable.
This can be solved by adding a serializer function to the Product class:
This will create a dictionary containing the member variables as key/value pairs.
So now the only thing left is to call this serializer function for each product before writing the data to the file.
After the list of products is prepared, i.e. made JSON serializable, the above function write_json_file can be called.