Convert JSON to Python Pydantic model!

Input JSON to generate Python Pydantic v2 BaseModel or dataclass code, including nested objects! Great for FastAPI models. SQLAlchemy models are in the tabs above.
JSON
Result
 

Convert JSON to Python Pydantic model!

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.

How to use

  1. Paste the JSON you want to model.
  2. Enter the top-level model name in Type name (for example Forecast).
  3. Under Style, pick Pydantic (v2) for validation and aliases, or dataclass for a dependency-free model.
  4. Copy the result into a module such as models.py. Style and type name are saved in the URL.

Example

Input (JSON)
{
  "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" }
  ]
}
Output (Python · Pydantic v2)
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.

Supported features

  • Pydantic v2: renamed fields use Field(alias=...), and model_config = ConfigDict(populate_by_name=True) lets you also populate them by their Python name.
  • dataclass: fields without defaults are moved ahead of = None fields to avoid TypeError: non-default argument follows default argument; the original key is kept as a # JSON: "updatedAt" comment.
  • Types: str, int, float, bool, list[...], and Any for values of mixed types.
  • Fields missing from some items or containing null become X | None = None.
  • Python keywords such as class, from or type get a trailing underscore (class_).
  • from __future__ import annotations is included so classes can reference each other regardless of order.
  • A top-level array produces an alias such as Root = list[RootItem].

Use cases

FastAPI response models and request bodies

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.

Validating third-party API responses

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.

Replacing dict lookups in scripts

Turning data["current"]["temp"] into forecast.current.temp gives you editor completion and lets mypy or pyright check the code.

Notes and limitations

  • @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.
  • To serialize back with the original JSON keys (updatedAt) in Pydantic, call model_dump(by_alias=True) or model_dump_json(by_alias=True).
  • The output uses str | None syntax, so the Pydantic models assume Python 3.10 or newer.
  • Date and time strings come out as str. With Pydantic, changing the annotation to datetime is enough to parse ISO 8601 values.
  • Pydantic v1 constructs (class Config, parse_obj) are not generated.

FAQ

What is 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.

I prefer 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.

Can it output TypedDict or attrs classes?

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.

Are aliases added when keys are already snake_case?

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.