How to use JSON to Python
- Paste a sample into JSON. For lists, paste several items so optional fields can be detected.
- Set the Class name for the top-level class.
- Choose a Style: TypedDict, dataclass or Pydantic model.
- Copy or download
models.py. Nested classes come first, so the file runs as it is.
What it does and when to use it
When a Python service consumes a JSON API, typed classes let your editor autocomplete fields and let a type checker catch typos such as order["totla"]. Writing those classes for a large response takes a while and is easy to get subtly wrong. Paste one real response and you get definitions to start from.
The same sample can produce Go structs or TypeScript interfaces if other services use it. To check later responses against a fixed contract instead of Python types, write a schema and test with the JSON Schema validator.
How it works
The tool reads the sample in your browser and builds one shape from it. Items in an array are merged, so a key missing from some items is optional: NotRequired[...] in TypedDict, or | None = None in dataclass and Pydantic, where optional fields are moved after required ones because Python needs defaults last. Whole numbers become int, a mix of whole and decimal numbers becomes float, and values that change type become a union such as str | int. Each nested object becomes a class named after its key in singular form, so items gives Item.
Worked examples
An order sample, Class name Order, style TypedDict (abridged):
from typing import Any, NotRequired, TypedDict
class Item(TypedDict):
sku: str
price: float
gift: NotRequired[bool]
class Order(TypedDict):
order_id: str
total: float
coupon: None
customer: Customer
items: list[Item]
tags: list[Any]
gift appears in only one of two items, so it is NotRequired. coupon was null and tags was empty, so both need a real type from you.
Pydantic style for {"orderId": "A-17", "class": "gold", ...}:
class Order(BaseModel):
order_id: str = Field(alias="orderId")
class_: str = Field(alias="class")
items: list[Item]
Limits and tips
- Types reflect only your sample. A string that holds a date stays
str; change it todatetimeby hand if you want parsing. - With Pydantic aliases, build models with
Order.model_validate(data); passingorder_id=directly needspopulate_by_namein the model config.
Frequently asked questions
Which style should I pick?
Which Python version does the output need?
Can I load JSON straight into the dataclass?
Why is a field typed None or list[Any]?
What happens to keys that are not valid Python names?
How do we know nothing is uploaded? Test it yourself on the privacy proof page.