Sub topic 4
Controlling JSON output: indent, sort_keys, and ensure_ascii
This chapter assumes you can call json.dumps and json.dump, open files with with, and read a short traceback. By default, json.dumps produces valid but hard-to-read text. Three keyword arguments change that: indent, sort_keys, and ensure_ascii. A fourth, separators, controls whitespace.
The default: compact single line
Without options, json.dumps writes everything on one line.
import json
data = {"name": "Ada", "langs": ["Python", "C"], "active": True}
print(json.dumps(data))
# {"name": "Ada", "langs": ["Python", "C"], "active": true}This is fine for machines. It is hard for people to read once the structure nests.
indent: make nesting visible
indent takes a number of spaces, or a string such as "\t". It puts each list item and each key on its own line.
import json
data = {"name": "Ada", "langs": ["Python", "C"], "active": True}
print(json.dumps(data, indent=2))# Output:
# {
# "name": "Ada",
# "langs": [
# "Python",
# "C"
# ],
# "active": true
# }indent=0 inserts newlines but no spaces. indent=None, the default, gives the single-line form. Use indent for config files, logs you read by eye, and files that go into version control. Skip it for network payloads, where the extra whitespace only adds bytes.
sort_keys: stable, comparable output
Dicts keep insertion order, so two dicts with the same content can serialize differently. sort_keys=True sorts keys alphabetically at every nesting level.
import json
a = {"b": 1, "a": 2}
b = {"a": 2, "b": 1}
print(json.dumps(a) == json.dumps(b)) # False
print(json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True)) # True
print(json.dumps(a, sort_keys=True)) # {"a": 2, "b": 1}Sorted output gives clean diffs in version control. It also lets you use the serialized text as a cache key or for a hash.
ensure_ascii: escaped or readable text
By default, json.dumps escapes every non-ASCII character as a \uXXXX sequence. The output is pure ASCII, which is safe on any channel, but it is unreadable to humans.
import json
data = {"city": "Zürich", "mood": "😀"}
print(json.dumps(data))
# {"city": "Z\u00fcrich", "mood": "\ud83d\ude00"}
print(json.dumps(data, ensure_ascii=False))
# {"city": "Zürich", "mood": "😀"}Characters outside the Basic Multilingual Plane, such as emoji, become a surrogate pair (\ud83d\ude00). Both forms decode back to the same Python string, so the choice affects only the text.
With ensure_ascii=False, the output can contain any Unicode character. The file or stream you write it to must then use an encoding that can represent it. In practice, open the file with encoding="utf-8", as covered in the first chapter. If you skip that, the platform default encoding may fail on write or silently produce a different encoding than the reader expects.
separators: compact or custom whitespace
separators is a tuple of (item_separator, key_separator). The defaults are (", ", ": ") without indent and (",", ": ") with it. For the smallest possible output, remove all spaces.
import json
data = {"a": 1, "b": [1, 2]}
print(json.dumps(data, separators=(",", ":")))
# {"a":1,"b":[1,2]}Combining options for files
json.dump accepts the same options as json.dumps. A common pattern for a human-edited, diff-friendly file is:
import json
from pathlib import Path
settings = {"theme": "dark", "city": "Zürich", "retries": 3}
path = Path("settings.json")
with path.open("w", encoding="utf-8") as f:
json.dump(settings, f, indent=2, sort_keys=True, ensure_ascii=False)
f.write("\n")json.dump does not add a trailing newline, so the example writes one. Many tools and editors expect text files to end with a newline.
Choosing options
| Goal | Options |
|---|---|
| Readable config file | `indent=2`, `ensure_ascii=False` |
| Stable diffs or hashing | `sort_keys=True` |
| Smallest payload | `separators=(",", ":")` |
| ASCII-only transport | leave `ensure_ascii` at its default, `True` |
Exercise
You call json.dumps({"z": 1, "é": 2}, sortkeys=True, ensureascii=False, separators=(",", ":")). What text does it return?
Show answer
{"z":1,"é":2}. The keys are sorted by code point, and "z" (U+007A) comes before "é" (U+00E9). ensure_ascii=False keeps the é unescaped, and the separators remove all spaces.
Exercise
A teammate writes json.dump(data, f, ensure_ascii=False) to a file opened without an encoding argument, and the output is garbled on another machine. What is the likely cause and the fix?
Show answer
Without an explicit encoding, open() uses the platform default, which may not be UTF-8, so the non-ASCII characters are written in a different encoding than the reader expects. Open the file with encoding="utf-8" on both the write and the read.