JSON to Pydantic model
Useful for FastAPI and similar projects: it writes a BaseModel per object that validates the data as it is read.
Loading the tool…
Processing and privacy: The result is calculated inside your browser and your data is not sent to any server.
How to use it
- Enter json input and root type name.
- The result appears straight away and updates as you edit.
- Copy the result, or copy a link that keeps the same values to share it.
How it is calculated
str, int, float, bool, List[T] and Any, with a BaseModel per nested object. Field names are snake_case, and when one differs from the JSON key it gets Field(alias="key"). null makes the type a required Optional[T], and a key missing from some items defaults to None.
Example
Inputs: Root type name = Root. Result: Generated code: from typing import List, Optional from pydantic import BaseModel class Order(BaseModel): order_id: str total: float coupon: Optional[str] class Address(BaseModel): city: str postal_code: str class Root(BaseModel): id: int name: str email: str is_active: bool balance: float tags: List[str] address: Address orders: List[Order]; Types generated: 3; Fields: 13.
{
"id": 1024,
"name": "Sara Ahmed",
"email": "sara@example.com",
"is_active": true,
"balance": 1520.75,
"tags": ["vip", "riyadh"],
"address": { "city": "Riyadh", "postal_code": "12211" },
"orders": [
{ "order_id": "A-1", "total": 99.5, "coupon": "EID10" },
{ "order_id": "A-2", "total": 120, "coupon": null }
]
}from typing import List, Optional
from pydantic import BaseModel
class Order(BaseModel):
order_id: str
total: float
coupon: Optional[str]
class Address(BaseModel):
city: str
postal_code: str
class Root(BaseModel):
id: int
name: str
email: str
is_active: bool
balance: float
tags: List[str]
address: Address
orders: List[Order]Limits and caveats
- The code targets Pydantic version 2.
- With an alias you pass data using the original JSON keys; to use the field names too, enable populate_by_name in model_config.
Questions about this tool
What does Field(alias) do?
It lets the Python field be snake_case while reading the original key, such as userId, from JSON.
Optional[str] versus Optional[str] = None?
The first means the key is always present but may be null; the second means the key may be missing from some items.
How do I load JSON with the model?
Use Root.model_validate(data) for a dict, or Root.model_validate_json(text) for a JSON string.
