Sub topic 6
Serializing dates and other custom types
This chapter assumes you can call json.dumps and json.loads, and that you know how Python maps JSON values to its own types (see the earlier chapters on the JSON data model and on reading and writing JSON). You should also be comfortable with isinstance, classes, and exceptions.
Why the json module refuses some objects
The json module knows how to write a fixed set of Python types: dict, list, tuple, str, int, float, bool, and None. Any other object makes json.dumps raise 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 serializableThe module does this on purpose. JSON has no date type, so any choice (a string, a Unix timestamp, an array of parts) is a decision about your data format. Python leaves that decision to you.
You make the decision in one place: a function that receives the object the encoder could not handle and returns something it can handle.
The default parameter
json.dumps and json.dump accept a default argument. It is a function the encoder calls for each object it cannot serialize. The function returns a replacement value, and the encoder serializes that replacement instead.
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"}Two rules keep this function correct:
- Return a value the encoder already supports, or another object that
defaultwill handle on a later call. The encoder callsdefaultagain on the result if it is still unsupported. - Raise
TypeErrorfor anything you do not recognize. If you returnNoneby accident, the unknown object silently becomesnullin the output, and the data loss is hard to notice.
Choosing a representation for common types
Pick one representation per type and use it everywhere. The table lists common choices.
| Python type | Common JSON form | Example output |
|---|---|---|
| `datetime`, `date` | ISO 8601 string | `"2026-11-26T10:50:00+00:00"` |
| `Decimal` | string | `"19.90"` |
| `UUID` | string | `"12345678-1234-5678-1234-567812345678"` |
| `Path` | string (POSIX form) | `"data/items.csv"` |
| `Enum` | its `.value` | `"active"` |
| `set`, `frozenset` | sorted list | `["gift", "rush"]` |
| dataclass instance | object (via `asdict`) | `{"x": 1, "y": 2}` |
ISO 8601 is the usual choice for dates. The strings sort correctly as text, other languages parse them, and datetime.fromisoformat reads them back.
Decimal as a string is deliberate. Writing it as a JSON number would force a conversion to float, which loses the exact decimal value. A string keeps it exact.
Sets have no defined order, so sort them. Otherwise the same data can produce different output on different runs, which breaks diffs and tests.
One function for many types
Real programs have several custom types. Put them all in one default function and check each with isinstance.
import json
from dataclasses import asdict, dataclass, is_dataclass
from datetime import date, datetime, timezone
from decimal import Decimal
from enum import Enum
from pathlib import Path
from uuid import UUID
class Status(Enum):
ACTIVE = "active"
CLOSED = "closed"
@dataclass
class Order:
id: UUID
placed: datetime
total: Decimal
status: Status
tags: set[str]
def encode(obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, (Decimal, UUID)):
return str(obj)
if isinstance(obj, Path):
return obj.as_posix()
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, (set, frozenset)):
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(
id=UUID("12345678-1234-5678-1234-567812345678"),
placed=datetime(2026, 11, 26, 10, 50, tzinfo=timezone.utc),
total=Decimal("19.90"),
status=Status.ACTIVE,
tags={"rush", "gift"},
)
print(json.dumps(order, default=encode, sort_keys=True))The output is one line:
{"id": "12345678-1234-5678-1234-567812345678", "placed": "2026-11-26T10:50:00+00:00", "status": "active", "tags": ["gift", "rush"], "total": "19.90"}Follow the flow for order. The encoder does not recognize the dataclass, so it calls encode, which returns a dict from asdict. The encoder then walks that dict. The UUID, datetime, Decimal, Status, and set values inside it are each unsupported, so encode is called again for each one.
The is_dataclass(obj) and not isinstance(obj, type) check matters. is_dataclass also returns True for the dataclass class itself, and asdict fails on a class.
Putting the logic in a JSONEncoder subclass
The default argument suits a script. If several modules share the same rules, or you want a reusable object, subclass json.JSONEncoder and override its default method. Pass the class with cls=.
import json
from datetime import date, datetime
class AppEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, (datetime, date)):
return o.isoformat()
return super().default(o)
print(json.dumps({"day": date(2026, 11, 26)}, cls=AppEncoder))
# {"day": "2026-11-26"}The last line, return super().default(o), replaces the explicit raise TypeError. The base class already raises the standard error message for unsupported types.
The two styles do the same job. Use the function when you need a one-off. Use the subclass when you want to name the behavior and reuse it with json.dump, json.dumps, or AppEncoder().encode(...).
What default cannot reach
default is only called for values. Three situations surprise people.
Dictionary keys
JSON object keys must be strings. The encoder converts int, float, bool, and None keys to strings itself, but it does not call default for keys of any other type.
import json
from datetime import date
try:
json.dumps({date(2026, 11, 26): 1})
except TypeError as e:
print(e) # keys must be str, int, float, bool or None, not date
print(json.dumps({1: "a", None: "b"})) # {"1": "a", "null": "b"}Convert such keys before encoding, for example {d.isoformat(): v for d, v in data.items()}. The second line of output also shows a silent change: an integer key 1 comes back as the string "1" when you load the text.
Values the encoder already accepts
default is skipped for any type the encoder supports. You cannot use it to change how a float or a tuple is written, because it is never asked. Subclasses of supported types, such as a dict subclass, are written as plain dict or list too. If you need a different form, convert the value yourself before calling dumps.
Special float values
float("nan") and float("inf") are valid Python floats, so default is not called. By default the encoder writes NaN or Infinity, which is not valid JSON, and many parsers reject it. Pass allow_nan=False to make the encoder raise ValueError instead.
import json
print(json.dumps(float("nan"))) # NaN
try:
json.dumps(float("nan"), allow_nan=False)
except ValueError as e:
print(e) # Out of range float values are not JSON compliantReading custom types back
Encoding is half the job. After json.loads, your date is a plain string. JSON carries no marker saying "this string was a datetime", so you must restore the types yourself. There are three common approaches.
Convert after loading
The simplest approach is to load the data and convert the fields you know about.
import json
from datetime import datetime
from decimal import Decimal
text = '{"placed": "2026-11-26T10:50:00+00:00", "total": "19.90"}'
data = json.loads(text)
data["placed"] = datetime.fromisoformat(data["placed"])
data["total"] = Decimal(data["total"])
print(data["placed"].year, data["total"] + 1) # 2026 20.90Convert during loading with object_hook
object_hook is a function the decoder calls with every decoded JSON object (as a dict). Whatever it returns replaces the dict. This suits data with many nested objects that share field names.
import json
from datetime import datetime
from decimal import Decimal
def decode(d):
if "placed" in d:
d["placed"] = datetime.fromisoformat(d["placed"])
if "total" in d:
d["total"] = Decimal(d["total"])
return d
text = '[{"placed": "2026-11-26T10:50:00+00:00", "total": "19.90"}]'
orders = json.loads(text, object_hook=decode)
print(orders[0]["placed"].tzinfo) # UTC+00:00The hook runs on inner objects before outer ones. It keys on field names, so two unrelated objects that both have a total field would be converted the same way. That is acceptable when you control the schema. If you do not, convert after loading.
Parse numbers as Decimal
If your JSON contains real numbers and you want exact decimals, json.loads accepts parse_float.
import json
from decimal import Decimal
data = json.loads('{"price": 19.90}', parse_float=Decimal)
print(repr(data["price"])) # Decimal('19.90')This reads the digits straight into Decimal, so the value never passes through float.
Pitfalls to check before you ship
- Naive and aware datetimes.
datetime(2026, 11, 26, 10, 50).isoformat()has no offset, while an aware one ends in+00:00. When a reader loads the text, a naive value stays naive. Store timezone-aware values in UTC, and usedatetime.now(timezone.utc)rather thandatetime.utcnow(), which returns a naive value. - Round trips are not automatic. An
Enumwritten as its value, or asetwritten as a list, does not come back as the same type. Decide where reconstruction happens and write it down. - Circular references. If an object refers to itself,
dumpsraisesValueError: Circular reference detected. Yourdefaultfunction can create such a cycle if it returns an object that contains the original. - Lossy fallbacks. Writing
return str(obj)as a catch-all hides bugs, because an unexpected object becomes text like<Foo object at 0x...>. RaisingTypeErrorsurfaces the problem at the point of writing. - Unstable output. Without
sort_keys=Trueand sorted sets, the same data can produce different text on different runs.
Exercises
Exercise
A colleague writes def encode(obj): if isinstance(obj, datetime): return obj.isoformat() with no other branch, and passes it as default. A dictionary containing a set is then passed to json.dumps. What happens, and what should the function do instead?
Show answer
The function returns None for the set (a function with no return on that path returns None), so the encoder writes null and the set's contents are lost without any error. The function should end with raise TypeError(f"Cannot serialize {type(obj).__name__}"), and a branch such as if isinstance(obj, (set, frozenset)): return sorted(obj) should handle sets.
Exercise
What does json.dumps({date(2026, 11, 26): "launch"}, default=encode) do when encode converts dates to ISO strings, and how do you fix it?
Show answer
It raises TypeError ("keys must be str, int, float, bool or None, not date"). The encoder never passes dictionary keys to default. Convert the keys before encoding, for example {d.isoformat(): v for d, v in data.items()}.
Exercise
You store Decimal("0.10") by writing it as a string, then read the file back with json.loads. Write the one line that turns the loaded field data["fee"] back into a Decimal, and say why the string form was a better choice than float(obj) in default.
Show answer
data["fee"] = Decimal(data["fee"]). A float cannot represent many decimal fractions exactly, so converting through float can change the value. The string keeps every digit, and Decimal(str) restores the exact value.