How to Pretty Print JSON in Python (3 Methods)
Python's standard library covers JSON pretty-printing completely — no packages needed. Here are the three methods, from the everyday one-liner to command-line piping, plus the gotchas that catch people.
Method 1: json.dumps with indent
import json
data = {"name": "Amina", "roles": ["admin", "editor"], "active": True}
print(json.dumps(data, indent=2))
Output:
{
"name": "Amina",
"roles": [
"admin",
"editor"
],
"active": true
}
Useful parameters:
indent=2— spaces per level (useindent="\t"for tabs).sort_keys=True— alphabetical key order, which makes diffs between two payloads meaningful.ensure_ascii=False— output real Unicode characters instead of\u00e9escapes. Almost always what you want for human-readable output.
Method 2: reading and writing files
import json
with open("config.json") as f:
data = json.load(f)
with open("config.pretty.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
Note the pairing: load/dump work with file objects, loads/dumps with strings. Mixing them up is the classic beginner error, and the resulting message (expected str, bytes or os.PathLike) does not obviously point at it.
Method 3: the command line — no script at all
Python ships a JSON pretty-printer as a module, perfect for piping:
# pretty print a file
python -m json.tool data.json
# pretty print an API response
curl -s https://api.example.com/users | python -m json.tool
# with sorted keys (Python 3.5+)
python -m json.tool --sort-keys data.json
This doubles as a validator: invalid JSON exits with an error and the line number. If you have jq installed, jq . does the same with colour — but json.tool is already on any machine with Python.
What about pprint?
from pprint import pprint
pprint(data)
pprint formats Python objects, not JSON: you get single quotes, True instead of true, and None instead of null. Fine for debugging your own dicts; wrong the moment the output needs to be JSON that anything else parses. If the result will be consumed, always use json.dumps.
Common gotchas
- Datetimes are not serialisable —
json.dumps(datetime.now())raises TypeError. Convert withdefault=stror serialise ISO strings explicitly. - Dict keys become strings — integer keys are silently converted, so a round trip does not return the identical structure.
- NaN sneaks through — Python happily emits
NaN, which is invalid JSON that other parsers reject. Passallow_nan=Falseto catch it at source.
And when you have a payload in your clipboard rather than in code, skip Python entirely: paste it into our free JSON formatter — it pretty-prints, validates with line numbers, and never uploads your data.