This converter turns a JSON structure into Pydantic v2 BaseModel classes or standard-library @dataclass code. Field names are rewritten to snake_case as Python style expects, and every nested object gets its own class.
Reach for it when defining FastAPI request and response schemas, when adding type hints to data you fetch with requests or httpx, or when cleaning up ETL and scraping scripts that dig through dicts by string keys.
Type name (for example Forecast).Style, pick Pydantic (v2) for validation and aliases, or dataclass for a dependency-free model.models.py. Style and type name are saved in the URL.{
"city": "Seoul",
"updatedAt": "2024-05-01T09:00:00+09:00",
"current": { "temp": 18.5, "humidity": 40 },
"hourly": [
{ "hour": 10, "temp": 19, "rain_mm": 0 },
{ "hour": 11, "temp": 20.5, "rain_mm": 0.4, "alert": "shower" }
]
}from __future__ import annotations
from pydantic import BaseModel, ConfigDict, Field
class Hourly(BaseModel):
hour: int
temp: float
rain_mm: float
alert: str | None = None
class Current(BaseModel):
temp: float
humidity: int
class Forecast(BaseModel):
model_config = ConfigDict(populate_by_name=True)
city: str
updated_at: str = Field(alias="updatedAt")
current: Current
hourly: list[Hourly]
updatedAt becomes the updated_at field, tied back to the original key with Field(alias="updatedAt"). In hourly, temp mixes integers and decimals so it becomes float, and alert, present only in the second item, is str | None = None. Classes are emitted child-first.
Field(alias=...), and model_config = ConfigDict(populate_by_name=True) lets you also populate them by their Python name.= None fields to avoid TypeError: non-default argument follows default argument; the original key is kept as a # JSON: "updatedAt" comment.str, int, float, bool, list[...], and Any for values of mixed types.null become X | None = None.class, from or type get a trailing underscore (class_).from __future__ import annotations is included so classes can reference each other regardless of order.Root = list[RootItem].Build BaseModels from the JSON you agreed on with the frontend and use them in response_model= or as endpoint parameters; the OpenAPI docs follow automatically.
Wrap calls in Forecast.model_validate(resp.json()) and when the provider changes a field type, ValidationError points to the exact field path that broke.
Turning data["current"]["temp"] into forecast.current.temp gives you editor completion and lets mypy or pyright check the code.
@dataclass does not convert nested dicts into objects. After Forecast(**data), current is still a dict; use Pydantic or a helper like dacite if you need nested conversion.updatedAt) in Pydantic, call model_dump(by_alias=True) or model_dump_json(by_alias=True).str | None syntax, so the Pydantic models assume Python 3.10 or newer.str. With Pydantic, changing the annotation to datetime is enough to parse ISO 8601 values.class Config, parse_obj) are not generated.populate_by_name=True for?By default an aliased field only accepts its alias (updatedAt) as input. With this setting you can also write Forecast(updated_at=...), which is handy in tests.
Optional[str] for optional fields.str | None and Optional[str] mean the same thing. If you need Python 3.9 compatibility, import Optional from typing and swap the annotations.
The supported styles are Pydantic v2 and dataclass. The dataclass field list carries over directly to a TypedDict or an @attrs.define class if you need one of those.
No. When the Python name equals the original key, no Field(alias=...) or ConfigDict is emitted, so you get plain lines like rain_mm: float.