How to Generate Python Dataclasses from JSON
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:
intvsfloat— whole numbers becomeint, decimals becomefloat.- 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
nullbecomesOptional[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.