Sub topic 6
Serializing dates and other custom types
This chapter assumes you can call json.dumps and json.dump, write functions, and catch exceptions. It builds on the earlier chapters about the JSON data model and about reading and writing JSON.
Why json refuses some objects
JSON has only strings, numbers, booleans, null, arrays, and objects. The json module can encode the Python types that map onto these. Anything else raises TypeError.
import json
from datetime import datetime
try:
json.dumps({"at": datetime(2026, 11, 26, 10, 50)})
except TypeError as e:
print(e) # Object of type datetime is not JSON serializableJSON has no date type, so the module cannot guess how you want a date written. You decide the representation. The usual choice for dates is an ISO 8601 string.
The default function
json.dumps and json.dump accept a default argument. It is a function the encoder calls for each object it cannot serialize itself. The function returns a value the encoder understands, and the encoder then serializes that value.
import json
from datetime import datetime
def encode(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Cannot serialize {type(obj).__name__}")
print(json.dumps({"at": datetime(2026, 11, 26, 10, 50)}, default=encode))
# {"at": "2026-11-26T10:50:00"}Handling several types in one function
Real data mixes types. Keep one default function and add a branch for each type. Return a JSON-friendly value from each branch.
import json
from dataclasses import asdict, dataclass, is_dataclass
from datetime import date, datetime
from decimal import Decimal
@dataclass
class Order:
id: int
placed: date
total: Decimal
tags: set
def encode(obj):
if isinstance(obj, (date, datetime)):
return obj.isoformat()
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, set):
return sorted(obj)
if is_dataclass(obj) and not isinstance(obj, type):
return asdict(obj)
raise TypeError(f"Cannot serialize {type(obj).__name__}")
order = Order(7, date(2026, 11, 26), Decimal("19.99"), {"rush", "gift"})
text = json.dumps(order, default=encode, sort_keys=True)
print(text)
# {"id": 7, "placed": "2026-11-26", "tags": ["gift", "rush"], "total": "19.99"}Each choice here has a reason:
datetimeis a subclass ofdate, and both haveisoformat(), so one branch covers them.Decimalbecomes a string. Converting it tofloatcould introduce rounding errors, which matters for money.- A
setbecomes a sorted list. Sets have no defined order, so sorting makes the output repeatable. asdictturns a dataclass into a dict. The encoder then callsdefaultagain for thedate,Decimal, andsetinside it.
Reading the values back
The conversion is one-way. json.loads returns plain strings, and your code has to convert them back.
import json
from datetime import date
from decimal import Decimal
text = '{"id": 7, "placed": "2026-11-26", "tags": ["gift", "rush"], "total": "19.99"}'
data = json.loads(text)
placed = date.fromisoformat(data["placed"])
total = Decimal(data["total"])
tags = set(data["tags"])
print(placed.year, total + 1, sorted(tags)) # 2026 20.99 ['gift', 'rush']If you store a decimal as a JSON number instead of a string, json.loads(text, parse_float=Decimal) parses every float as a Decimal.
Common errors
- Returning the same object from
default. The encoder callsdefaultagain and detects a loop. You getValueError: Circular reference detected. Always raiseTypeErrorfor types you do not handle. - Using a custom type as a dictionary key.
defaultis not called for keys.json.dumps({date(2026, 11, 26): 1})raisesTypeError. Convert keys yourself, for example{d.isoformat(): v}. - Forgetting
defaultinjson.dump. It takes the same argument asjson.dumps. Pass it in both places if you use both. - Assuming a round trip. A date written as a string comes back as a string. Nothing in the JSON marks it as a date, so your loading code must know which fields to convert.
Exercise
A dictionary contains a datetime value and a set value. You call json.dumps(data, default=encode), where encode handles only datetime and ends with raise TypeError(...). What happens, and how do you fix it?
Show answer
The datetime is written as an ISO string, but the set reaches the TypeError at the end of encode, so json.dumps fails. Add a branch such as if isinstance(obj, set): return sorted(obj) before the final raise.
Exercise
You serialize {"due": date(2026, 12, 1)} with a working default and later read it with json.loads. What is the type of data["due"], and how do you get a date back?
Show answer
It is a str, "2026-12-01". Convert it with date.fromisoformat(data["due"]).