json Module: Custom Encoders, Hooks, and StreamingBeyond basic loads() and dumps(), Python's json module includes hooks for serializing custom objects like datetime or Decimal, formatting compact API payloads, and parsing newline-delimited JSON streams.
Using these options keeps API serializers clean without pulling in heavy external dependencies for simple scripts.
default=When json.dumps() encounters an object it does not recognize—such as a datetime or dataclass—it calls your default callback to convert it into a JSON-safe type.
from datetime import date
from decimal import Decimal
import json
def json_fallback(obj):
if isinstance(obj, date):
return obj.isoformat()
if isinstance(obj, Decimal):
return float(obj)
raise TypeError(f"Unsupported type: {type(obj).__name__}")
invoice = {"issued": date(2026, 11, 12), "total": Decimal("149.95")}
print(json.dumps(invoice, default=json_fallback, sort_keys=True))
For network responses, pass separators=(",", ":") to strip whitespace and shrink payload bytes. When processing multi-gigabyte log exports, write one JSON object per line (NDJSON) and iterate line by line instead of loading one giant array.
lines = ['{"id": 1, "ok": true}', '{"id": 2, "ok": false}']
records = [json.loads(line) for line in lines]
print(records[1]["ok"])
float(Decimal(...)) when exact cents matter: Converting money Decimal values to string (str(obj)) preserves exact decimal precision across JSON APIs.json.load(): Full-file loading buffers every object in RAM; use NDJSON lines or streaming parsers like ijson.ensure_ascii=False: By default json.dumps() escapes non-ASCII characters as \uXXXX; set ensure_ascii=False for readable UTF-8 output.object_hook in json.loads() do?object_hook passes every decoded dictionary through a custom function so you can transform keys or turn dicts into typed objects during parsing.
sort_keys=True?Sorting keys creates deterministic JSON output, which makes snapshot tests, cache keys, and checksum comparisons reliable.
json.loads() parse trailing commas or comments?No. The strict JSON RFC forbids comments and trailing commas. Strip them or use a TOML/YAML parser if you need human-edited config comments.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.