Pretty Printing JSON
By default, dumps() produces compact JSON on one line. That's efficient but hard to read. Use the indent parameter for pretty output.
import json
data = {"name": "Alice", "address": {"city": "NYC", "country": "USA"}}
# Compact (default)
print(json.dumps(data))
# {"name": "Alice", "address": {"city": "NYC", "country": "USA"}}
# Pretty
print(json.dumps(data, indent=2))
With indent=2, you get:
{
"name": "Alice",
"address": {
"city": "NYC",
"country": "USA"
}
}
For sorted keys (helpful for diffs):
json.dumps(data, indent=2, sort_keys=True)
Pretty printing is great for debugging and config files. For API responses and storage, stick with compact format to save space.
I cover JSON formatting options in my JSON with Python course.