AllOneTools Logo
AllOneTools

Python guide · 4 min read

How to pretty-print JSON in Python

Format JSON in Python with json.dumps, pprint, rich, and CLI (python -m json.tool). Handles Unicode, sorting keys, custom indentation, and big files.

Last updated:

[object Object]

1 Method 1 — Command line (no code needed)

[object Object]

[object Object]

[object Object]

[object Object]

[object Object]

[object Object]

2 Method 2 — json.dumps() in code

[object Object]

[object Object]

[object Object]

[object Object]

[object Object]

    [object Object]

3 Method 3 — Custom encoder for dates, Decimals, and big ints

[object Object]

[object Object]

4 Method 4 — rich for colored output in terminals

[object Object]

[object Object]

[object Object]

5 Method 5 — Streaming big JSON files

[object Object]

[object Object]

[object Object]

Frequently asked questions

Why do non-ASCII characters show up as `\u00e9` in my output?

Default behavior of `json.dumps`. Pass `ensure_ascii=False` to preserve Unicode, and make sure you write the file with `encoding='utf-8'` so the bytes round-trip correctly.

How do I pretty-print a string that's already JSON?

Parse then re-serialize: `json.dumps(json.loads(json_string), indent=2)`. If it's a file: `python -m json.tool input.json > pretty.json`.

Which is faster — `json` or `orjson`?

`orjson` is 2–10× faster than the stdlib `json` module and returns bytes directly. For read-heavy APIs it's a huge win. Downside: no `indent` parameter with the exact same API — use `orjson.OPT_INDENT_2` flag instead.

Can I preserve key order?

Python 3.7+ preserves dict insertion order, and `json.dumps` preserves that order by default. Don't pass `sort_keys=True` if you want to keep your original ordering.

Keep exploring