Pretty Print a JSON File in Python

People use the JSON format to store and read data easily. By default, Python sends a minified version of Python, to save memory and bandwidth. But when you try to debug, it’s easier to read the beautified version of a JSON file.

In this lesson, I’m going to show how to save a JSON file, how to display it, and what is most important, how to pretty print it on the console.

import json

filename = 'file.json'
json_write = ['foo', {'bar': ('baz', 5, None, 1.7)}]

with open(filename, 'w') as f_obj:
    json.dump(json_write, f_obj)

This code creates a JSON file – “file.json” and writes the json_write list to a file.

Let’s display json data using the following code:

import json

filename = 'file.json'

with open(filename) as f_obj:
    json_load = json.load(f_obj)

print(json.dumps(json_load))

If you try to display this data, you are going to get the following output:

["foo", {"bar": ["baz", 5, null, 1.7]}]

Pretty print JSON

It’s time to display the JSON file in beautified mode. This code is very similar to the previous one, where we displayed the result, but this time we are going to set additional parameters in json.dumps.

import json

filename = 'file.json'

with open(filename) as f_obj:
    json_load = json.load(f_obj)

print(json.dumps(json_load, sort_keys=True, indent=4, separators=(',', ': ')))

This code will display the following result.

[
     "foo",
     {
         "bar": [
             "baz",
             5,
             null,
             1.7
         ]
     }
 ]

sort_keys = True means that the output of dictionaries will be sorted by key and the indent is 4.