Sub topic 4
Controlling JSON output: indent, sort_keys, and ensure_ascii
This chapter assumes you can already call json.dumps and json.dump and know how JSON values map to Python types. It covers the options that change how the text looks without changing the data it describes: indent, sort_keys, ensure_ascii, separators, and a few related switches.
Why output formatting matters
json.dumps returns one line of text by default. That is fine for a network request, but hard to read in a log, a config file, or a code review. Formatting options let you choose the right text for each use:
- Human-readable files: indent them and sort the keys.
- Compact payloads: remove all optional whitespace.
- Files that contain non-English text: decide whether to escape or keep the characters.
- Files under version control: make the output the same every time, so diffs show only real changes.
All of these produce valid JSON that json.loads reads back to the same Python objects. Only the text differs.
The default output
import json
data = {"name": "Ada", "langs": ["Python", "C"], "active": True, "score": None}
print(json.dumps(data))The output is a single line:
{"name": "Ada", "langs": ["Python", "C"], "active": true, "score": null}The default puts a space after each , and after each :. The keys keep the order in which they were inserted into the dict.
Pretty-printing with indent
Passing indent makes dumps write each item on its own line and indent nested levels.
import json
data = {"name": "Ada", "langs": ["Python", "C"], "address": {"city": "London"}}
print(json.dumps(data, indent=2)){
"name": "Ada",
"langs": [
"Python",
"C"
],
"address": {
"city": "London"
}
}The value of indent controls the style:
| Value | Result |
|---|---|
| `None` (default) | A single line |
| `0` | Newlines, but no indentation |
| A positive integer such as `2` or `4` | That many spaces per nesting level |
| A string such as `"\t"` | That string once per nesting level |
Two details are worth remembering:
indent=0is not the same asindent=None. Zero still inserts newlines.- Empty containers stay compact.
{"items": []}prints as"items": []and not on separate lines.
import json
print(json.dumps({"rows": [], "meta": {}}, indent=2))
print(json.dumps({"a": [1, 2]}, indent="\t"))Writing indented JSON to a file
json.dump takes the same keyword arguments as json.dumps.
import json
from pathlib import Path
settings = {"theme": "dark", "tabs": [4, 8]}
with Path("settings.json").open("w", encoding="utf-8") as f:
json.dump(settings, f, indent=2)
f.write("\n")json.dump does not add a final newline. Many editors and tools expect text files to end with one, so write it yourself, as above.
Stable output with sort_keys
With sort_keys=True, every object is written with its keys in sorted order, at all nesting levels.
import json
a = {"b": 1, "a": 2}
b = {"a": 2, "b": 1}
print(json.dumps(a)) # {"b": 1, "a": 2}
print(json.dumps(a, sort_keys=True)) # {"a": 2, "b": 1}
print(json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True)) # TrueSorting is useful in three situations:
- Version control. If different code paths build the same dict in different orders, unsorted output creates noisy diffs. Sorted output does not.
- Comparisons and hashing. Two equal dicts always produce the same text, so you can compare or hash the text. This is a common way to build a cache key.
- Tests. You can compare output against an expected string without worrying about insertion order.
Gotcha: sorting needs comparable keys
JSON object keys are strings, but Python lets you use other key types, and dumps converts int, float, bool, and None keys to strings. Sorting happens on the original keys, so mixing types fails.
import json
try:
json.dumps({1: "a", "b": "c"}, sort_keys=True)
except TypeError as e:
print(e)Python cannot compare 1 with "b", so it raises TypeError. Without sort_keys, the same call works and gives {"1": "a", "b": "c"}. Keep keys the same type, or convert them to strings first.
A related surprise: sorting is by string order for string keys. The key "10" sorts before "2".
import json
print(json.dumps({"2": "b", "10": "a"}, sort_keys=True))
# {"10": "a", "2": "b"}Sorting does not reorder lists
sort_keys only affects objects. Lists keep their order, because order is part of a list's meaning.
Non-ASCII text and ensure_ascii
By default, dumps writes only ASCII characters. Any other character becomes a \u escape sequence. This is the ensure_ascii=True behavior.
import json
city = {"city": "Zürich", "greeting": "こんにちは"}
print(json.dumps(city))
print(json.dumps(city, ensure_ascii=False)){"city": "Z\u00fcrich", "greeting": "\u3053\u3093\u306b\u3061\u306f"}
{"city": "Zürich", "greeting": "こんにちは"}Both strings are valid JSON and both decode to the same Python dict. The difference is only in the text.
Characters outside the Basic Multilingual Plane, such as many emoji, are written as a surrogate pair of two escapes:
import json
print(json.dumps("😀")) # "\ud83d\ude00"
print(json.loads(json.dumps("😀")) == "😀") # TrueChoosing a value
| Setting | Strength | Cost |
|---|---|---|
| `ensure_ascii=True` (default) | Safe in any ASCII-only channel and any file encoding | Hard for people to read; text is longer |
| `ensure_ascii=False` | Readable, shorter | You must write the text in an encoding that can hold the characters, normally UTF-8 |
The main failure with ensure_ascii=False happens when the file is opened with the wrong encoding.
import json
with open("out.json", "w", encoding="ascii") as f:
try:
json.dump({"city": "Zürich"}, f, ensure_ascii=False)
except UnicodeEncodeError as e:
print("encode failed:", e.reason)The json module produces a Python string. Turning that string into bytes is the file object's job, and it uses the encoding you passed to open. If you omit encoding, Python uses a platform-dependent default, and the same script can behave differently on different machines. Always pass encoding="utf-8" when you use ensure_ascii=False, as the previous chapter on opening files recommends.
import json
from pathlib import Path
path = Path("city.json")
with path.open("w", encoding="utf-8") as f:
json.dump({"city": "Zürich"}, f, ensure_ascii=False, indent=2)
print(path.read_text(encoding="utf-8"))Compact output with separators
The separators argument is a pair (item_separator, key_separator). It controls the text written between items and between a key and its value.
The defaults depend on indent:
| `indent` | Default `separators` |
|---|---|
| `None` | `(", ", ": ")` |
| Any other value | `(",", ": ")` |
The second row avoids trailing spaces at the end of lines, since each item is already on its own line.
To get the smallest valid output, remove all optional spaces:
import json
data = {"id": 7, "tags": ["a", "b"], "ok": True}
default = json.dumps(data)
compact = json.dumps(data, separators=(",", ":"))
print(default)
print(compact)
print(len(default), len(compact)){"id": 7, "tags": ["a", "b"], "ok": true}
{"id":7,"tags":["a","b"],"ok":true}Compact output is the right choice for payloads sent over a network, for values stored in a database column, and for keys built from JSON text. Combine it with sort_keys=True when you need a canonical form:
import json
def canonical(obj):
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
print(canonical({"b": [1, 2], "a": {"y": 1, "x": 2}}))
# {"a":{"x":2,"y":1},"b":[1,2]}This is stable for a given Python version and input, but it is not a formal standard canonicalization such as RFC 8785. For example, it does not normalize how floats are written. Do not use it where another system must produce byte-identical output.
Other output options
A few more keyword arguments affect the text and are worth knowing.
allow_nan: Python can holdfloat("nan")andfloat("inf"). By default,dumpswrites them asNaNandInfinity, which are not valid JSON. Setallow_nan=Falseto raiseValueErrorinstead, which is the safer choice when other systems will read the result.skipkeys: IfTrue, keys that are notstr,int,float,bool, orNoneare silently dropped instead of raisingTypeError. Silent data loss is rarely what you want, so leave it off unless you have a specific reason.check_circular: Detects an object that contains itself and raisesValueError. It is on by default.
import json
try:
json.dumps({"x": float("nan")}, allow_nan=False)
except ValueError as e:
print(e)Choosing options for common tasks
| Task | Suggested call |
|---|---|
| Config file edited by people | `indent=2`, `ensure_ascii=False`, `sort_keys=True`, UTF-8 file, final newline |
| Log line or API request body | `separators=(",", ":")` |
| Cache key or content hash | `sort_keys=True`, `separators=(",", ":")` |
| Output for a strict ASCII-only consumer | Default `ensure_ascii=True` |
| Output that other tools must parse strictly | Add `allow_nan=False` |
Here is the first row as a reusable function:
import json
from pathlib import Path
def save_config(path, data):
with Path(path).open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2, sort_keys=True, ensure_ascii=False)
f.write("\n")
save_config("app.json", {"name": "Café", "retries": 3, "debug": False})
print(Path("app.json").read_text(encoding="utf-8"))Flow of the options
The options apply in two steps. The encoder first walks the Python object and decides the order of keys and the form of each value. It then writes text using the separators and indentation you chose, and ensure_ascii decides how non-ASCII characters appear. The file object turns the final text into bytes.
Common mistakes
- Expecting
indentto change the data. It never does.json.loads(json.dumps(x, indent=4)) == xholds for anyxthat round-trips. - Forgetting the encoding with
ensure_ascii=False. The code works on one machine and fails or garbles text on another. - Mixing key types with
sort_keys=True. This raisesTypeError. - Relying on sorted output for lists. Lists are not sorted. Sort them yourself first if their order should not matter.
- Comparing pretty-printed text from different sources. Compare parsed objects, or write both with the same options.
Exercise
You write json.dump({"name": "Zoë", "n": 1}, f, ensure_ascii=False) to a file opened with open("out.json", "w") and no encoding. It works on your laptop but fails on a colleague's machine with UnicodeEncodeError. Explain why, and give the fix.
Show answer
With ensure_ascii=False, json.dump passes the character ë straight to the file object. The file object encodes it using the platform default encoding, because open was called without encoding. On a machine whose default cannot represent ë, encoding fails. The fix is to open the file with an explicit encoding: open("out.json", "w", encoding="utf-8"). Keeping the default ensure_ascii=True would also avoid the error, because the output would then be pure ASCII.
Exercise
Write a function fingerprint(obj) that returns the same string for any two dicts that are equal, regardless of key insertion order, using the smallest valid JSON text. Then say what happens for {1: "a", "b": "c"}.
Show answer
Use import json and def fingerprint(obj): return json.dumps(obj, sort_keys=True, separators=(",", ":")). Two equal dicts produce the same text because keys are sorted at every level and no optional whitespace is written. For {1: "a", "b": "c"}, sort_keys=True makes Python compare the int 1 with the str "b", so json.dumps raises TypeError. Convert the keys to strings before calling it.
Exercise
What is the difference between indent=0 and indent=None, and what does json.dumps({"a": []}, indent=2) print for the empty list?
Show answer
indent=None writes everything on one line. indent=0 writes each item on its own line with no leading spaces. For {"a": []} with indent=2, the empty list stays compact, so the output is { then "a": [] then }, on three lines.