Python Pretty Print JSON

This article will cover the process of pretty-printing JSON in Python. JSON (JavaScript Object Notation) is a popular data format with diverse uses in data manipulation and transmission. When dealing with large and complex JSON files in Python, it’s often useful to “pretty-print” them.

Python’s json Module

Python comes with a built-in module called json for encoding and decoding JSON data. Among other functionalities, this module provides the necessary tools for pretty-printing JSON data.

Here’s how to pretty print JSON using the json module:

import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

json_str = json.dumps(data, indent=4)
print(json_str)

In this script, json.dumps() is a method that converts a Python object into a JSON string. The indent the parameter specifies how many spaces to use as an indentation.

When we run this script, it outputs:

Python Pretty Print JSON
Python Pretty Print JSON

Pretty Printing JSON From a File

Often, you’ll need to Python pretty print JSON data stored in a file. Let’s take a look at how you can achieve this:

import json

with open('file.json', 'r') as f:
    data = json.load(f)

pretty_json = json.dumps(data, indent=4)
print(pretty_json)

Here, json.load() is used to load JSON data from a file. Then we pretty-print the data as before.

Output:

Python Pretty Print JSON example
Python Pretty Print JSON example

Pretty Printing JSON using pprint Module

Python also has a module named pprint for pretty printing. This can be particularly useful for nested data structures. Let’s see how to use it for pretty printing JSON data:

import json
from pprint import pprint

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

pprint(data)

The pprint() function prints the given data in a “pretty” format with both indentations and sorting.’

Output:

Pretty Printing JSON using pprint Module
Pretty Printing JSON using pprint Module

Conclusion

Python provides excellent support for pretty-printing JSON data, either from an object or from a file, using either the json module or the pprint module. This can be a great help when you’re working with complex JSON structures. Remember, pretty printing not only makes your JSON data more readable but also can help to detect errors or anomalies in your data.

You may like to read: