How to Serialize a Dataclass to JSON in Python
Serialize a Python dataclass instance to JSON using asdict and json.dumps for API responses or mocks.
Python code
15 linesfrom dataclasses import dataclass, asdict
import json
@dataclass
class UserResponse:
id: int
name: str
email: str
active: bool = True
if __name__ == "__main__":
response = UserResponse(id=42, name="Ada Lovelace", email="ada@example.com")
print(json.dumps(asdict(response), indent=2))
Output
{
"id": 42,
"name": "Ada Lovelace",
"email": "ada@example.com",
"active": true
}
How it works
The asdict function recursively converts the dataclass instance into a plain dictionary, turning nested dataclasses into nested dicts. Then json.dumps serializes that dictionary to a JSON string, with indent=2 producing readable multi-line output. Because dataclasses are not natively JSON-serializable, using asdict bridges the gap cleanly. This pattern is common in API layers where you need to return a response object as JSON.
Common mistakes
- Calling json.dumps directly on the dataclass instance, which raises TypeError
- Forgetting to handle non-serializable fields like datetime without a custom encoder
- Using dataclasses.asdict which deep-copies nested objects, unlike dataclasses.astuple
Variations
- Use dataclasses.astuple if you need a tuple instead of a dict
- Create a custom json.JSONEncoder subclass that handles dataclasses directly without asdict
Real-world use cases
- Mocking an API response in unit tests before it's wired to a real endpoint.
- Converting a user record from a database query into a JSON payload for a REST endpoint.
- Serializing event data in a serverless function to send to a downstream HTTP service.
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.