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.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 13 views 0 copies

Python code

15 lines
Python 3.9+
from 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

stdout
{
  "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

  1. Use dataclasses.astuple if you need a tuple instead of a dict
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.