Python JSON Module
Python json Module: Custom Encoders, Hooks, and Streaming
Beyond 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.
Custom Serialization with 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))
Compact Output and Streaming NDJSON
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"])
Common Mistakes to Avoid
- Using
float(Decimal(...))when exact cents matter: Converting moneyDecimalvalues to string (str(obj)) preserves exact decimal precision across JSON APIs. - Loading 2GB JSON arrays with
json.load(): Full-file loading buffers every object in RAM; use NDJSON lines or streaming parsers likeijson. - Forgetting
ensure_ascii=False: By defaultjson.dumps()escapes non-ASCII characters as\uXXXX; setensure_ascii=Falsefor readable UTF-8 output.
Frequently Asked Questions
What does 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.
Why use sort_keys=True?
Sorting keys creates deterministic JSON output, which makes snapshot tests, cache keys, and checksum comparisons reliable.
Can 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.