Python Friday #95: Working With JSON

If you work with web technologies these days, there is no way around JSON. Today we look at the basic operations to serialize our objects to JSON and turn JSON back into objects.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

JSON in Python

JSON (JavaScript Object Notation) is a lightweight data interchange format. In Python we can use the built-in json module in a similar way to pickle. We do not need to install anything and can start with importing json in our code:

 

Save as JSON

We can reuse the same example data from the post on PrettyPrinter:

We can create a JSON string with the dumps() method directly in-memory, without the need to write it to a file as we did with the similar method for pickle. I create a file only for the purpose of loading JSON in the next part:

This code creates a data.json file with this content:

If you want to change the separator or sort the keys, you can do that the same way as I did with the indentation on the method call for dumps().

 

Load from JSON

We can turn a JSON string back to objects with the loads() method:

If we run this code, we get this output:

 

Conclusion

Working with JSON in Python is surprisingly painless and you do not need to install anything. All you need is a method call and your objects are in the JSON format.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.