JSON to Pydantic Model

Infer Pydantic models from a JSON sample.

About JSON to Pydantic Model

Generate Pydantic models from a JSON sample. Paste JSON and BaseModel classes appear as you type, one model per nested object, with date fields typed.

How to use

  1. Paste JSON, or load a .json file (up to 5 MB).
  2. Optionally change the root model name (default Root). It must start with a letter or underscore and contain only letters, digits and underscores, up to 64 characters.
  3. The Python code updates as you type. Copy it, or Download it as a .py file.

Inference rules

  • Integers become int, other numbers float, booleans bool, strings str, and null becomes Optional[Any].
  • A string matching YYYY-MM-DD becomes date; an ISO 8601 timestamp becomes datetime. No validator is generated, because Pydantic parses ISO strings into these types on its own.
  • A list becomes List[T], mixed types List[Union[...]] (int and float together collapse to float), and an empty list List[Any].
  • A nested object becomes its own BaseModel subclass named after its path, for example RootAddress or RootUserAddress, listed before the model that uses it. An empty object becomes a model with pass.
  • A list of objects is typed from all its items: a key missing from some items becomes Optional[T] = None.
  • A key that is not a valid Python identifier is renamed to snake_case and kept as an alias, for example first_name: str = Field(alias="first-name"), so the JSON still loads with model_validate.
  • The header imports only what the models use. No constraints are added.

Example

{ "id": 1, "joined": "2024-01-31" }
→
from pydantic import BaseModel
from datetime import date

class Root(BaseModel):
    id: int
    joined: date

Privacy

Inference runs in the page. No request is made and nothing is stored.

Frequently asked questions

What is the difference between a Pydantic model and a dataclass?
A dataclass only stores fields; its type hints are not checked at runtime. A Pydantic BaseModel validates and coerces each field when an instance is created, so bad JSON fails early with a clear error.
How do I create a Pydantic model from JSON?
Define a BaseModel subclass with one annotated field per key, then call Root.model_validate(data) in Pydantic 2 (Root.parse_obj in Pydantic 1). Nested models are validated recursively.
Is @validator still supported in Pydantic 2?
Yes, but it is deprecated. Pydantic 2 keeps @validator for compatibility and emits a warning; new code should use @field_validator with mode="before" for the same pre-parsing behaviour.
Why do date fields have no validator?
Pydantic parses ISO 8601 strings into date and datetime on its own and raises a ValidationError for anything else, so a hand-written validator would only repeat that. Add a field_validator if you need to accept another format.