"category": "code-generator",
JSON to Python Dataclass Generator
"tldr": Paste JSON and get Python dataclasses with type hints - snake_case fields, nested classes, an easy starting point for Pydantic.
Turn a JSON payload into Python dataclasses with full type hints. Keys are converted to snake_case, nested objects become their own dataclasses, and arrays become list[T] with the element type inferred from the data.
Typed classes beat raw dicts the moment a payload is used in more than one place: attribute access with IDE autocomplete, mypy checking, and a single definition of the shape instead of string keys scattered through the codebase.
How to convert JSON to Python dataclasses
- 1Paste a representative JSON payload into the input panel.
- 2Each nested object becomes a dataclass, defined before the classes that reference it.
- 3Keys are snake_cased; if your JSON is already snake_case the names match one-to-one.
- 4Copy the classes into your project - construct them manually, or upgrade to Pydantic for parsing (see FAQ).
Convert JSON to Python dataclass in code
import json
from dacite import from_dict # pip install dacite
data = json.loads(text)
order = from_dict(data_class=Root, data=data)
print(order.customer.name)from pydantic import BaseModel # pip install pydantic
class Customer(BaseModel):
name: str
email: str
class Root(BaseModel):
order_id: int
total: float
customer: Customer
order = Root.model_validate_json(text) # parses and validatesFrequently asked questions
How do I load JSON into these dataclasses?
Dataclasses do not parse JSON by themselves - Root(**json.loads(text)) works only for flat objects. For nested structures use dacite (from_dict) or convert the definitions to Pydantic models, which validate and construct the whole tree with Root.model_validate_json(text).
Should I use Pydantic instead?
If the JSON comes from an external source (API, user input), yes - Pydantic validates types at runtime and reports precise errors. The generated dataclasses convert almost mechanically: change @dataclass to class Root(BaseModel) and remove the decorator.
What about keys that were camelCase in the JSON?
The generator snake_cases field names, so "orderId" becomes order_id. Plain dataclasses have no aliasing, so either keep the original key spelling as the field name, or use Pydantic with alias generators (populate_by_name + to_camel) to map both spellings.
Why is a null field typed as Any?
One sample with null gives no information about the real type. In practice such fields are Optional[str], Optional[float], etc. - update them based on what the API documents or a more complete sample.
Last updated:
You might also need
Free and in-browser, like everything on JSON Console. Browse all tools →