How to Generate Python Dataclasses from JSON

By Ramanathan Aug 11, 2026 1 min read JSON to Python

Typing out Python classes to match a JSON API response is tedious. Generating dataclasses from a real sample is faster and gives you type hints for free. Here's how the mapping works.

From JSON to dataclasses

Each JSON object becomes a @dataclass, and nested objects become their own dataclasses referenced by name:

{ "id": 1, "name": "Ada", "address": { "city": "London" } }
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, List, Optional, Union


@dataclass
class Root:
    id: int
    name: str
    address: Address


@dataclass
class Address:
    city: str

The from __future__ import annotations line lets a class reference another that's defined lower in the file.

Optional fields, unions, and null

Types are inferred from the values:

  • int vs float — whole numbers become int, decimals become float.
  • Optional — when you convert an array of objects and a key is missing from some of them, it's typed Optional[...].
  • Union — a field with different value types across samples becomes Union[int, str].
  • null — a field whose sample value is null becomes Optional[Any], because its real type can't be inferred. Replace it with the correct type.

Switching to Pydantic

The output is standard dataclasses, but the type hints are what matter. To use Pydantic, change @dataclass / class X: to class X(BaseModel): — the field annotations carry straight over.

Related

Generating types for another language? See JSON to TypeScript, or the Complete Guide to JSON.

Try it

Paste a JSON response and get Python dataclasses instantly — everything runs in your browser, nothing uploaded.

About the author

Ramanathan · Software Engineer & Solutions Architect

I'm a Software Engineer and Solutions Architect with 20+ years of experience building enterprise applications across BFSI, Healthcare, Retail, Manufacturing, and Industrial Automation. I've spent those two decades living in JSON, tokens, regexes, and config files — so I built the fast, private, no-login developer tools I always wanted to reach for myself.

Last updated: Aug 11, 2026