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
- Paste JSON, or load a
.jsonfile (up to 5 MB). - 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. - The Python code updates as you type. Copy it, or Download it as a
.pyfile.
Inference rules
- Integers become
int, other numbersfloat, booleansbool, stringsstr, andnullbecomesOptional[Any]. - A string matching
YYYY-MM-DDbecomesdate; an ISO 8601 timestamp becomesdatetime. No validator is generated, because Pydantic parses ISO strings into these types on its own. - A list becomes
List[T], mixed typesList[Union[...]](intandfloattogether collapse tofloat), and an empty listList[Any]. - A nested object becomes its own
BaseModelsubclass named after its path, for exampleRootAddressorRootUserAddress, listed before the model that uses it. An empty object becomes a model withpass. - 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 withmodel_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.