How to beautify and pretty print formatted JSON in Python
JSON in few words
JSON (i.e. JavaScript Object Notation) syntax is based on a subset of the JavaScript programming language. It is a simple, easy to read, write, parse and transform data exchange format. JSON is extremely popular in building REST based web services. Recall that not only JSON but also other formats such as XML can be used to exchange data. This article is not the right venue to debate which is better.
So et us get started…
Why do we need to beautify JSON
Beatification of source code makes it easy to read which is handy when debugging and testing. Of course, production code is encouraged to be minified specially in web applications as it reduces download time. Before we jump to the main topic, let us briefly describe what JSON is…
Making sense of JSON
An easy way to make sense of JSON data format is to think of it like a database table. Data in a database table is organized into rows (records) and columns (fields). Similarly, JSON can be used to serialize data in the form of programming language objects (primitive data types, arrays and dictionaries) to be stored on disk.
Let us take an example…
1 2 3 4 |
[{"name": "John","address": {"street": "8 bit avenue", "zip": "94444", "city": "San Jose"}}, {"name": "Chris","address": {"street": "4 bit avenue", "zip": "95555", "city": "Milpitas"}}] |
In the above example, here are few observations…
- name is a key and John is the corresponding value, or a column value in a database table
- [] is an array, in this example, we have two records or two rows in a database
- {} is used to represent dictionaries to map keys to values
Online code beautification tools
If you want to quickly beautify the example JSON data above without writing code, you can do so online easily. There are few tools that just do that. For example…
- Go to jsoneditoronline.org
- Paste the JSON file in the left side of the screen
- Click the right arrow and see how the JSON file will look like
We are going to do something similar. The above JSON file is typically transmitted as one long ugly string.
JSON beatification
Just take a look at the following Python code snippet. The code is explained in details using comments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# JSON module is used to convert json data # in string format to Python objects and # visa versa. This is known as serialization import json # Example JSON strng. Note that we are using # three double quote string so that we can # use multiline strings s_json = """[{"name": "John","address": {"street": "8 bit avenue", "zip": "94444", "city": "San Jose"}}, {"name": "Chris","address": {"street": "4 bit avenue", "zip": "95555", "city": "Milpitas"}}]""" # When parsing JSON anything can go wrong # So we need to handle exceptions. For example # If the JSON fails validation, the exception # is triggered try: # Load JSON data from a string to Python object o_json = json.loads(s_json) # Convert the JSON Python object back to string # Also format it in a nice way. That is what # this article is all about. The indent parameter # specifies the width of the indentation which is # self explanatory. The sorted_keys parameter # specifies if we want to keep the input JSON # as is or sort the key. In this case we are not f_json = json.dumps(o_json, indent = 3, sort_keys=False) # Print the beautified JSON print(f_json) # Catch any exceptions except Exception as ex: # repr is used to print more information about # the object which is handy when debugging print(repr(ex)) |
How to format a JSON file
If JSON data is stored in a disk file, we can easily apply the same technique. The only difference is that we just need to add file IO code. Here is an example code snippet that demonstrate how to read/write a JSON string from/to file…
1 2 3 4 5 6 7 |
# Instead of reading from string read from file as follows with open("input.json") as f: s_json = f.read() # Instead of printing to console print to file with open("out.json","w") as f: f.write(f_json) |
JSON formatting from the command line
We can format and validate a JSON file on the fly using the terminal. Assume that the JSON data file mentioned earlier is saved to a file called input.json. We can do so by typing the following command
1 |
cat input.json | python -m json.tool |
Please note the following…
- m option allows Python to load a module from the command line
- json.tool validates and pretty print the JSON file
If you execute the command above you should get the following output…
Thanks for reading. Please use the comments below for questions.