Pretty print JSON in Python
Indent it, sort it, and format a file without writing a script.
To pretty print JSON in Python, call json.dumps with an indent. The json module is in the standard library, so there is nothing to install.
The short answer
import json
data = {"name": "Nitro", "stars": 120, "tags": ["python", "static"], "archived": False}
print(json.dumps(data, indent=2))
{
"name": "Nitro",
"stars": 120,
"tags": [
"python",
"static"
],
"archived": false
}
indent=2 puts every key and every list item on its own line, indented two spaces per level. Use indent=4 if you prefer four, or indent="\t" for tabs.
Pretty print a JSON string or file
Text that is already JSON has to be parsed first, then written back out:
ugly = '{"name":"Nitro","tags":["python","static"],"stars":120}'
print(json.dumps(json.loads(ugly), indent=2))
A file works the same way. Read it, then either print it or write the tidy version back with json.dump:
with open("data.json", encoding="utf-8") as f:
loaded = json.load(f)
with open("data.json", "w", encoding="utf-8") as f:
json.dump(loaded, f, indent=2)
There is more on the second half in writing a JSON file.
Sort the keys
Keys come out in the order the dict holds them. sort_keys=True puts them in alphabetical order at every level, which makes two files much easier to diff:
json.dumps({"b": 2, "a": {"d": 1, "c": [3, 1]}}, sort_keys=True)
Lists are left alone. Their order is part of the data.
Keep accented characters readable
By default every non-ASCII character is escaped, which is safe but hard to read:
json.dumps({"city": "Zürich"}) # '{"city": "Z\\u00fcrich"}'
json.dumps({"city": "Zürich"}, ensure_ascii=False) # '{"city": "Zürich"}'
Both are valid JSON and parse back to the same string. If you write the second form to a file, open the file with encoding="utf-8".
From the command line
Python ships a small formatter you can run without writing any code:
python -m json.tool data.json
python -m json.tool --sort-keys --indent 2 data.json
python -m json.tool data.json pretty.json
curl -s https://api.github.com/repos/python/cpython | python -m json.tool
It indents by four spaces unless you pass --indent, reads from standard input when you give it no file, and writes to a second filename if you supply one. --no-ensure-ascii keeps accented characters as they are, and --compact goes the other way and strips all the whitespace. It also doubles as a validator: on invalid input it prints the parse error and exits with a non-zero status.
pprint or json.dumps?
pprint is for Python objects, not JSON. It looks similar at a glance, but the output is a Python literal:
import pprint
pprint.pprint(data, width=40)
{'archived': False,
'name': 'Nitro',
'stars': 120,
'tags': ['python', 'static']}
Single quotes, and False where JSON wants false. It also sorts keys unless you pass sort_dicts=False. That is fine for a quick look while debugging, and it keeps short lists on one line, which json.dumps will not do. If the output is going into a file, an API or someone else's parser, use json.dumps.
The opposite: compact output
When the reader is a program, drop the whitespace:
json.dumps(data, separators=(",", ":"))
# '{"name":"Nitro","stars":120,"tags":["python","static"],"archived":false}'
The json.dumps recipe covers separators and the other arguments.
The shorter way with Nitro DataStore
Nitro DataStore will not format JSON any better than json.dumps does. What it saves is the read-and-write-back dance, because save indents by two spaces and leaves non-ASCII characters alone by default:
from nitro_datastore import NitroDataStore
store = NitroDataStore.from_file("data.json")
store.save("pretty.json")
print(json.dumps(store.to_dict(), indent=2))
That is not a reason to install it. If you already use it to read and edit JSON files, the files it writes are tidy without extra arguments. For pretty printing alone, stick with the standard library.
Common questions
Does indent change the data? No. Only whitespace between tokens changes, and any JSON parser reads both versions the same way.
Can I keep short lists on one line? Not with the json module. Once indent is set, every list item gets its own line. pprint keeps them together, but its output is not JSON.
Why is there a space after each colon and comma? The default separators are ", " and ": ". Pass separators=(",", ":") to remove them.
How do I pretty print without sorting? Leave sort_keys out. The default keeps the order of the dict.
Related
json.dumps in Python
Turn a dict into JSON text, and teach it about dates, decimals and sets.
Read ->Write JSON to a file in Python
Save a dict as JSON, change it later, and never leave a half-written file behind.
Read ->Read a JSON file in Python
Open a JSON file, get a dict back, and handle the three ways it goes wrong.
Read ->This page uses Nitro DataStore.
Read JSON with dot notation and a chainable query builder. No schema to define, no ORM to learn.
$ pip install nitro-datastore