Pretty printing and compact output

json · Essentials · 7 min

Readable JSON helps humans and diffs; compact JSON saves bandwidth.

json.dumps and json.dump take formatting options:

  • indent=2 pretty-prints with nested indentation (an int or a string like "\t"). The default None produces a single line.
  • sort_keys=True orders 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 (",", ": ") when indent is set.
  • ensure_ascii=False writes non-ASCII characters as-is. By default they are escaped ("é" becomes "\u00e9"), which is valid but unreadable. When writing files with ensure_ascii=False, make sure the file is opened with encoding="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-keys

Options 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

  • indent pretty-prints; separators=(',', ':') gives the most compact form
  • sort_keys=True makes output stable for diffs and tests
  • ensure_ascii=False keeps Unicode readable; pair it with UTF-8 files

Check yourself

  1. Which option makes two equal dicts with different insertion orders produce identical JSON text?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/json.html#json.dumps