Mateen Kiani
Published on Mon Aug 11 2025·3 min read
Working with JSON in Python is straightforward thanks to the built-in json module. However, when you need to read or share JSON data, the compact output can be hard to scan. A quick fix is to pretty print JSON with indentation and sorted keys, making it far more readable for debugging or documentation.
In this guide, we'll explore several ways to pretty print JSON in Python. We'll cover the basics of the json module, show how to read and write JSON files with pretty output, discuss the pprint module, and introduce third-party libraries for more control and performance.
JSON is key in APIs, config files, and data exchange. While machine readability favors compact JSON, humans benefit from structure:
When troubleshooting API responses or reviewing configuration files, pretty printed JSON lets you spot missing or misplaced data quickly. It also improves logs, making issues stand out. Ultimately, readable data saves time and reduces errors.
The simplest way to pretty print JSON is with the json.dumps function:
import jsondata = {'name': 'Alice', 'age': 25, 'city': 'New York'}pretty = json.dumps(data, indent=4)print(pretty)
Add more options:
pretty_sorted = json.dumps(data, indent=2, sort_keys=True)print(pretty_sorted)
Parameters:
These options make output clear and consistent.
Reading and writing JSON files with pretty printing is just as easy. Start by loading your data:
import jsonwith open('data.json', 'r') as f:data = json.load(f)
Then write with indentation:
with open('pretty_data.json', 'w') as f:json.dump(data, f, indent=4)
Tip: Use separators=(',', ': ') to control spacing between items.
For more details on dumping JSON to files, see our guide: how to dump JSON to a file in Python.
The pprint module offers a general pretty printer for Python objects. It's handy for quick debugging:
from pprint import pprintdata = {'name': 'Alice', 'age': 25, 'languages': ['Python', 'JavaScript']}pprint(data)
pprint output uses its own formatting rules. It may differ from json.dumps especially for nested structures.
For large data or advanced features, consider third-party tools:
Example with rich:
from rich import print_jsonprint_json(data=data)
rich highlights syntax and colors, making terminal output even clearer.
Pretty printing adds overhead, especially for large JSON. If speed matters:
Measure with timeit to find the best option.
Pretty printing JSON in Python transforms compact, machine-centric data into readable output for humans. Using the built-in json module with indent and sort_keys meets most needs. For quick debugging, pprint works well, and for more powerful features, explore libraries like rich or orjson. Choose the right tool based on your workflow: readability, performance, or level of detail. Clear data leads to efficient development and easier troubleshooting.