JSON to Pydantic v2 model converter

Paste JSON and get Pydantic v2 BaseModel classes: str | None = None for keys that are missing or null, list[...] for arrays, nested models, and Field(alias=...) with populate_by_name for keys that aren't Python names. A standard-library dataclass version and the v1 to v2 differences are included.

Updated

Nested models are named from their keys: orders becomes Order.

Pydantic v2 models

3 classes, 14 fields

no aliases needed

Pydantic v2 models

from datetime import datetime

from pydantic import BaseModel


class Address(BaseModel):
    city: str
    pin_code: str


class Order(BaseModel):
    order_id: int
    total: float
    coupon: str | None = None
    note: str | None = None


class User(BaseModel):
    id: int
    first_name: str
    is_active: bool
    balance: float
    created_at: datetime
    address: Address
    tags: list[str]
    orders: list[Order]


# Usage
obj = User.model_validate_json(raw)   # from a JSON string
obj = User.model_validate(data)       # from a dict
data = obj.model_dump()
  • In Pydantic v2, Optional[X] or X | None with no default is still a required field that merely accepts None. That is why every optional or nullable field here ends in = None, which makes the key optional too.
  • Pydantic v2 comes from `pip install pydantic`. Methods renamed from v1: .dict() is model_dump(), .json() is model_dump_json(), parse_obj() is model_validate(), parse_raw() is model_validate_json(), and class Config became model_config.

How are Pydantic models worked out from JSON?

Each JSON object becomes a class that inherits BaseModel, and each key a typed field: str, int, float, bool, datetime for ISO 8601 date-times, list[T] for arrays and another model for nested objects. For an array of objects, every item is read together, so a key present in only some items, or null in some, becomes optional. A number is int unless any value has a decimal part, and then float.

A key that can be missing or null is written X | None = None. In Pydantic v2 a bare Optional with no default is a required field that accepts None, so the explicit default is what makes the key optional. Keys that aren't valid Python names (camelCase, hyphens, keywords like class) get a snake_case field name and Field(alias="originalKey"), and the model gets populate_by_name so either spelling can be used to build it.

Models are written so each one comes after the models it uses, which Python needs for plain annotations. The dataclass option writes the same structure with the standard library and a from_dict() on each class to build nested objects; it does not check types, so it is a lighter alternative when you already trust the data.

"firstName": "Asha"            -> first_name: str = Field(alias="firstName")
"coupon": null / key missing     -> coupon: str | None = None
"tags": ["a", "b"]              -> tags: list[str]

What changed between Pydantic v1 and v2 for models?

The renames and behaviour changes that matter when you paste generated code
Pydantic v1Pydantic v2Why it matters here
Optional[str] with no default is optionalOptional[str] with no default is required (accepts None)Generated fields end in = None
class Config:model_config = ConfigDict(...)Alias and extra settings use it
allow_population_by_field_namepopulate_by_name (validate_by_name from 2.11)Needed when a field has an alias
.dict().model_dump()Use by_alias=True to get the JSON keys back
.json().model_dump_json()
parse_obj(), parse_raw()model_validate(), model_validate_json()Usage lines at the end
Field(regex=...)Field(pattern=...)Not generated, but common when you add rules
__root__ modelsRootModelNot needed; a top-level array uses TypeAdapter

How to turn JSON into Pydantic models

  1. 1
    Paste a real responseFor a list, include several items so keys that come and go are seen. A JSON error shows its line and column.
  2. 2
    Choose the stylePydantic v2 models for validation, or standard-library dataclasses if you only need typed containers. Set the Python version style and whether unknown keys should be rejected.
  3. 3
    Copy the codeSave it as models.py. Install pydantic with pip if you chose the Pydantic output.
  4. 4
    Validate your dataCall model_validate_json(raw) for a JSON string, or model_validate(data) for a parsed dict. A mismatch raises a ValidationError that names the field.

Frequently asked questions

Why does Pydantic say my Optional field is required?
In v2, Optional[str] only means the value may be None; without a default the field must still be supplied. This is a v1 to v2 change. Write Optional[str] = None or str | None = None to make the key itself optional, which is what this page generates.
What is Field(alias=...) for?
It tells Pydantic that the JSON key is named differently from the Python attribute. With alias="firstName", validation reads firstName and the attribute is first_name. Add populate_by_name=True (validate_by_name from 2.11) in model_config if you also want to construct the model with first_name.
How do I get the original JSON keys back out?
Call model_dump(by_alias=True) for a dict or model_dump_json(by_alias=True) for a string. Without by_alias the output uses the Python attribute names such as first_name.
How do I validate a JSON array at the top level?
Use TypeAdapter(list[User]).validate_json(raw). In v1 this was a __root__ model; in v2 RootModel exists but TypeAdapter is lighter for one-off validation. The usage lines at the end of the output show the right form for your JSON.
Should I pick Pydantic or a dataclass?
Pick Pydantic when the data comes from outside your program (an API, a file) and you want wrong types rejected with a clear error. A dataclass is enough for data you already trust; it stores whatever you pass and converts nothing.
Why was one of my field names changed?
Python keywords (class, from, import), names that would shadow a BaseModel attribute (json, dict, copy, schema, model_dump and the other model_ methods), and names starting with a digit can't be used as they are. The field gets a safe name and the original key is kept as its alias.
Can I paste an API response that contains private data?
The page runs entirely in your browser and sends nothing out, so the response is not uploaded. As good practice, replace real names, tokens and ids with dummy values anyway; the model only needs the shape.

Sources

Related tools

See all 135 free tools

Need a custom dev tool for your team?

We build internal tools, dashboards, APIs, and SaaS platforms. If you can describe it, we can ship it.

Built by CountryDevs · No signup · No ads · We count visits, never what you enter