Pass a custom default= serializer function (such as default=vars or a type-dispatch function) to json.dumps(obj, default=...), or subclass json.JSONEncoder and override its default(self, o) method to convert your custom class instance into a JSON-native dictionary, list, or primitive—using dataclasses.asdict() automatically if your class is a .
Basic Example
from dataclasses import asdict, dataclass, is_dataclass
from datetime import datetime
import json
# 1. Standard custom class
class User:
def __init__(self, user_id: int, username: str, created_at: datetime) -> None:
self.user_id = user_id
self.username = username
self.created_at = created_at
def to_dict(self) -> dict:
return {
"user_id": self.user_id,
"username": self.username,
"created_at": self.created_at.isoformat(),
}
# 2. Recommended: Pass a `default=` fallback function to json.dumps()
def json_serializer(obj: object) -> object:
if hasattr(obj, "to_dict"):
return obj.to_dict()
if is_dataclass(obj) and not isinstance(obj, type):
return asdict(obj)
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
user = User(101, "alice", datetime(2026, 11, 28, 11, 44))
print(json.dumps(user, default=json_serializer, indent=2))
# Output:
# {
# "user_id": 101,
# "username": "alice",
# "created_at": "2026-11-28T11:44:00"
# }
Key Details & Edge Cases
- Why
default=varsworks for simple classes—and where it fails:- Passing
json.dumps(obj, default=vars)serializes any instance’s__dict__in a single expression without extra code. - However,
vars(obj)fails withTypeError: vars() argument must have __dict__ attributeif your class defines__slots__(without__dict__), and it exposes private attributes (_password,_cache) unless you filter them in a customto_dict()method.
- Passing
- Avoid inheriting from
dict(class User(dict):) as a shortcut:- Subclassing
dictmakesjson.dumps(user)work withoutdefault=, but it silently ignores instance attributes stored onself(self.name = "Alice") unless duplicated inside the underlying dictionary, and breaks standard object semantics (isinstance(user, dict)becomesTrue).
- Subclassing
- Subclassing
json.JSONEncoderfor reusable library-wide encoders:- When integrating with frameworks (like Flask or custom logging handlers) that accept an encoder class (
cls=CustomEncoder), subclassjson.JSONEncoder:class CustomEncoder(json.JSONEncoder): def default(self, o: object) -> object: if hasattr(o, "to_dict"): return o.to_dict() return super().default(o) # Raises standard TypeError for unsupported types payload = json.dumps(user, cls=CustomEncoder) - Always delegate unknown types to
super().default(o)instead of returningNone—returningNonesilently turns unsupported objects into JSONnullrather than raising a helpfulTypeError.
- When integrating with frameworks (like Flask or custom logging handlers) that accept an encoder class (
- Recursive nested objects (
json.dumpsinvokesdefault()automatically at every level):- You do not need to recursively serialize nested custom objects inside
to_dict(). Wheneverto_dict()returns adictorlistcontaining another custom object (e.g.,Addressordatetime),json.dumps()automatically calls yourdefault=handler again on those inner values.
- You do not need to recursively serialize nested custom objects inside
- Round-trip deserialization (
json.loads(..., object_hook=...)):- JSON has no native custom-class tags, so
json.loads()always produces plaindictobjects unless you include a type marker (e.g.,"__type__": "User") into_dict()and reconstruct instances via anobject_hookfunction—or use Pydantic (BaseModel.model_dump_jso()/User.model_validate_json()) for automatic schema-validated round-trip serialization.
- JSON has no native custom-class tags, so
Comparison of Custom Class JSON Serialization Approaches
| Approach | Syntax | Handles Nested Objects & datetime? |
Supports __slots__ Classes? |
Best Used When |
|---|---|---|---|---|
json.dumps(..., default=fn) |
json.dumps(obj, default=json_serializer) |
Yes (called recursively by json) |
Yes (via to_dict() or asdict()) |
Cleanest, idiomatic standard-library solution for custom domain models. |
json.dumps(..., default=vars) |
json.dumps(obj, default=vars) |
Only if fields are JSON-native | No (requires __dict__) |
Quick one-liner for simple data-holding classes with primitive attributes. |
json.JSONEncoder Subclass |
json.dumps(obj, cls=CustomEncoder) |
Yes | Yes | Passing an encoder class to third-party APIs or centralizing app-wide serialization rules. |
+ dataclasses.asdict |
json.dumps(asdict(dc_obj)) |
Nested dataclasses only (not datetime) |
Yes () |
Pure data containers defined with where all fields are primitives/lists/dicts. |
Pydantic BaseModel (3rd-party) |
obj.model_dump_jso() |
Yes (built-in datetime, UUID, Path) |
Yes | Production APIs needing automatic JSON serialization, validation, and deserialization. |
You must log in or register to comment.
