Represent Custom Values in JSON
Core idea
JSON cannot directly encode every Python type. Convert a value explicitly to a documented representation, or supply a default callable to dumps for otherwise unsupported objects. Decode only the expected representation and validate the shape; do not reconstruct arbitrary classes from external type labels.
from decimal import Decimalimport jsonamount = Decimal("12.30")wire = json.dumps({"amount": str(amount)})restored = Decimal(json.loads(wire)["amount"])print(wire, str(restored))The agreed field is a decimal string, so its trailing zero survives.
Encode one supported custom type
import jsonfrom decimal import Decimaldef encode_extra(value): if isinstance(value, Decimal): return str(value) raise TypeError("unsupported value")print(json.dumps({"price": Decimal("0.10")}, default=encode_extra))default runs for the unsupported Decimal and returns a supported string; it does not automatically decode the string later.
Common mistake
Avoid default=str as a catch-all if fidelity matters. An unsupported value may silently become ambiguous text. Explicit conversion and a schema make intent testable.
Practice
Encode a Fraction as a dictionary with numerator and denominator, then validate integer fields and a nonzero denominator before restoring it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Custom JSON representation
Check your understanding of json custom encoding.
What is printed?
import jsonfrom decimal import Decimalprint(json.dumps(Decimal("1.20"), default=str))What is printed?
import jsonfrom decimal import Decimalprint(type(json.loads("1.25", parse_float=Decimal)).__name__)When is default called by dumps?
Which decoding design is safer for external data?