Readable JSON helps humans and diffs; compact JSON saves bandwidth.
json.dumps and json.dump take formatting options:
indent=2pretty-prints with nested indentation (an int or a string like"\t"). The defaultNoneproduces a single line.sort_keys=Trueorders object keys alphabetically, giving stable output for diffs, tests and caching.separators=(",", ":")removes the spaces after commas and colons for the most compact form. The default is(", ", ": "), or(",", ": ")whenindentis set.ensure_ascii=Falsewrites non-ASCII characters as-is. By default they are escaped ("é"becomes"\u00e9"), which is valid but unreadable. When writing files withensure_ascii=False, make sure the file is opened withencoding="utf-8".
From the shell, python -m json.tool file.json validates and pretty-prints a file, and it reads stdin when no file is given:
curl -s https://api.example.com/x | python -m json.tool --sort-keysOptions include --indent, --compact, --sort-keys and --json-lines.
Formatting never changes the data, only whitespace and key order, so any JSON parser reads all variants identically.
Example
import json
order = {"id": 42, "customer": "Zoë", "items": [{"sku": "A1", "qty": 2}]}
print(json.dumps(order))
# {"id": 42, "customer": "Zo\u00eb", "items": [{"sku": "A1", "qty": 2}]}
print(json.dumps(order, ensure_ascii=False, separators=(",", ":")))
# {"id":42,"customer":"Zoë","items":[{"sku":"A1","qty":2}]}
print(json.dumps(order, indent=2, sort_keys=True, ensure_ascii=False))
# {
# "customer": "Zoë",
# "id": 42,
# "items": [
# {
# "qty": 2,
# "sku": "A1"
# }
# ]
# }Remember
indentpretty-prints;separators=(',', ':')gives the most compact formsort_keys=Truemakes output stable for diffs and testsensure_ascii=Falsekeeps Unicode readable; pair it with UTF-8 files