Optional[...] = None, and lists are typed. No boilerplate, no install.Consuming an API in Python is far nicer with real types: editor autocomplete, static checks with mypy/pyright, and clear data contracts. Hand-writing dataclasses for a big response is tedious — here's how to generate correct ones in seconds.
From JSON to dataclasses in 3 steps
- Paste a JSON object or API response into the converter.
- Name the root class — nested objects get their own dataclasses automatically.
- Copy the dataclasses or download a
.pyfile.
A real example
{ "id": 1, "name": "Jane", "address": { "city": "X", "zip": "12345" } }becomes:
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Address:
city: str
zip: str
@dataclass
class Root:
id: int
name: str
address: AddressOptional fields (done right)
When you paste an array of objects, a good generator looks across all of them. A key present in some records but missing in others becomes Optional[T] = None — and, crucially, those defaulted fields are emitted after the required ones, so the dataclass is valid Python (fields with defaults must come last, or Python raises TypeError: non-default argument follows default argument).
@dataclass
class UserItem:
id: int
name: str
email: Optional[str] = None
User = List[UserItem]Types, lists, and unions
Numbers map to int or float, booleans to bool, strings to str. Arrays become List[T]; mixed arrays become List[Union[int, str]]. The output uses from __future__ import annotations so forward references between classes just work regardless of order.
Tips
- Paste a representative array, not one record, so Optional fields are detected.
- Name the root after the entity (
User,Order). - Validate first if the JSON won't parse — use the JSON Validator.
- Prefer Pydantic? The dataclass shape maps cleanly onto a
BaseModel.
FAQ
Which Python version? 3.7+. The output uses the dataclasses and typing modules.
Is my data uploaded? No — conversion runs entirely in your browser.
Need TypeScript or Java instead? See JSON to TypeScript and JSON to Java.
Convert JSON to Python free →Related free tools: JSON to TypeScript · JSON Schema Generator · All JSON Tools