Pretty-print JSON files and responses in Python

Format JSON with indentation, preserve Unicode, validate API responses, and use Python’s json.tool from the command line.

Best practices
Python programming and application logging

Read JSON into a Python object, then serialize it with json.dumps(data, indent=4). Add ensure_ascii=False when you want non-ASCII characters displayed directly instead of as Unicode escape sequences.

Read and format a file

import json

with open("data.json", encoding="utf-8") as source:
    data = json.load(source)

print(json.dumps(data, indent=4, ensure_ascii=False))

json.load reads from a file-like object; json.loads parses a JSON string. Invalid JSON raises json.JSONDecodeError. This approach loads the complete document, so account for memory use with large inputs.

Choose formatting options

import json

data = {"city": "Montréal", "count": 3}
print(json.dumps(
    data,
    indent=4,
    ensure_ascii=False,
    sort_keys=True,
    separators=(",", ": "),
))

indent controls indentation. sort_keys sorts object keys for consistent presentation. separators controls the comma and colon separators. Sorting affects the displayed order, not the meaning of a JSON object.

For compact output, omit indentation and remove optional separator spaces:

compact = json.dumps(data, ensure_ascii=False, separators=(",", ":"))

Format an API response

With the third-party Requests package installed:

import json
import requests

response = requests.get("https://api.example.com/data", timeout=10)
response.raise_for_status()
data = response.json()
print(json.dumps(data, indent=2, ensure_ascii=False))

Replace the illustrative endpoint with your API. A successful HTTP response is not necessarily JSON; decoding can still fail. Set a timeout and handle transport, HTTP, and decoding failures according to the caller's needs.

Use the command line

python3 -m json.tool data.json
python3 -m json.tool --no-ensure-ascii data.json
cat data.json | python3 -m json.tool

json.tool validates and formats its input. The --no-ensure-ascii option is available in Python 3.9 and later.

FAQ

Are Unicode escapes corrupted text? No. Escaped and unescaped representations can describe the same string. ensure_ascii=False changes presentation; the terminal or output file still needs an encoding that supports the characters.

Does this produce strict JSON for every Python value? Not automatically. Unsupported objects raise TypeError, and Python permits non-finite floats by default when serializing. Use allow_nan=False if your output must reject NaN and infinity.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting