Module 15 · Python Standard Libraries — topic 8 of 13
json
The json module in depth: compact and pretty output, sorting keys, ensure_ascii, separators, serialising custom types with default=, decoding with object_hook, and error handling.
Learning objectives
- Control JSON output formatting
- Serialise custom types with default
- Rebuild custom types with object_hook
Definition
json encodes Python objects as JSON text (dumps/dump) and decodes JSON text into Python objects (loads/load). Hooks let you extend it to types JSON doesn't support natively, such as dates and sets.
Introduction
Basic JSON saving is one line, but real data includes dates, sets and custom classes. The json module's options and hooks handle them cleanly.
Why it matters
APIs and configuration files demand precise JSON. Knowing the options lets you produce exactly the format other systems expect.
Detailed explanation
dumps(obj) returns compact JSON; indent=2 pretty-prints; sort_keys=True orders keys for stable output.
separators=(",", ":") removes spaces for the smallest output; the default is (", ", ": ").
ensure_ascii=True (the default) escapes non-ASCII characters as \uXXXX; ensure_ascii=False keeps them readable.
Unsupported objects raise TypeError. The default= function is called for each such object and must return something serialisable (or raise TypeError).
loads(text, object_hook=func) calls func on every decoded dictionary, letting you convert values back into richer types.
dataclasses.asdict converts a dataclass to a dictionary, a convenient first step before dumping.
Invalid JSON raises json.JSONDecodeError with msg, lineno and colno.
JSON numbers have no separate integer and decimal types in the standard, but Python keeps the distinction: 3 loads as int and 3.0 as float. Use parse_float=decimal.Decimal when exact decimal values such as prices matter.
Syntax
- Options control formatting.
- default= serialises custom types.
- object_hook rebuilds them.
Code examples
Formatting options
{"b": 2, "a": [1, 2], "ok": null}
{"a":[1,2],"b":2,"ok":null}
"\u0928\u092e\u0938\u094d\u0924\u0947" "नमस्ते"Pretty-printing
{
"name": "Asha",
"skills": [
"py",
"sql"
]
}More examples
Dates and sets round trip
[{"title": "report", "due": "2026-12-01", "tags": ["urgent", "work"]}]
01 Dec date
cannot serialise objectStep-by-step explanation
- encode turns dates into ISO strings and sets into sorted lists; anything else is rejected with a clear TypeError.
- decode runs for every dictionary while loading and turns the due string back into a date.
- The round trip keeps the data's meaning even though JSON has no date type.
Expected output
Running “Dates and sets round trip” prints exactly:
Practical applications
- APIs exchanging timestamps as ISO strings.
- Saving application state that contains custom objects.
Best practices
- Use ISO strings for dates.
- Raise TypeError in default for unknown types.
- Use sort_keys for stable, diff-friendly files.
Common mistakes
Returning None from default
Avoid
Prefer
Returning None silently writes null for unknown objects.
Important notes
- json.JSONEncoder can be subclassed as an alternative to default=.
Key takeaways
- indent, sort_keys, separators and ensure_ascii control output.
- default= encodes custom types.
- object_hook decodes them.
Try it yourself
- 1Serialise a list of Decimal prices as strings and load them back as Decimal.
- 2Produce minified and pretty versions of the same JSON and compare their sizes.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?