Last updated:
JSON to Pydantic Converter
Paste a JSON example and this JSON to Pydantic converter writes Pydantic v2 models for it: a BaseModel per object, snake_case field names with aliases back to the JSON keys, and Optional where a field can be null or missing.
How This Works
All conversions use JSON Schema as an intermediate representation. Your JSON Example input is first read into a JSON Schema, then converted to Python Pydantic. What a format can't express is listed under the output. All processing happens in your browser — your schemas are never sent to a server.
How to use it
Paste a JSON value on the left, such as an API response or a message from a queue. The Python appears on the right as you type, and Copy or Download (models.py) takes it away. Set From to JSON Schema to convert a schema instead, with its constraints.
The JSON stays in your browser. The converter first infers a JSON Schema from it, with the same engine as the JSON to Schema Generator, then writes the models from that schema. The file runs on Python 3.9 or later with Pydantic 2.
Example: a flight booking
A booking with camelCase keys, two keys that are Python keywords, a date, a date-time, and a passenger whose seat isn't assigned yet:
{
"bookingRef": "QX7K2P",
"from": "LHR",
"to": "JFK",
"departsOn": "2026-12-01",
"passengers": [
{ "firstName": "Ann", "lastName": "Lee", "seat": "14C", "frequentFlyer": "BA123456" },
{ "firstName": "Bo", "lastName": "Lee", "seat": null }
],
"fare": { "amount": 412.6, "currency": "GBP" },
"class": "economy",
"confirmedAt": "2026-11-09T18:04:11+00:00"
} Field names become snake_case with an alias back to the JSON key, and populate_by_name=True lets your code use either name. from and class are Python keywords, so they become from_ and class_. departsOn is a date, so it's a datetime.date, and confirmedAt a datetime.datetime; Pydantic parses the strings into those types.
The two passengers are merged into one model. seat is in both but null in one, so it's Optional[str] with no default: required, but it may be None. frequentFlyer is in one passenger only, so it gets = None as a default and may be left out.
The converter's Python Pydantic output:
from __future__ import annotations
import datetime
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
class RootPassenger(BaseModel):
model_config = ConfigDict(populate_by_name=True)
first_name: str = Field(alias="firstName")
last_name: str = Field(alias="lastName")
seat: Optional[str]
frequent_flyer: Optional[str] = Field(default=None, alias="frequentFlyer")
class RootFare(BaseModel):
amount: float
currency: str
class Root(BaseModel):
model_config = ConfigDict(populate_by_name=True)
booking_ref: str = Field(alias="bookingRef")
from_: str = Field(alias="from")
to: str
departs_on: datetime.date = Field(alias="departsOn")
passengers: List[RootPassenger]
fare: RootFare
class_: str = Field(alias="class")
confirmed_at: datetime.datetime = Field(alias="confirmedAt")
RootPassenger.model_rebuild()
RootFare.model_rebuild()
Root.model_rebuild() Example: a JSON Schema with constraints
A JSON example can only say what a value looks like. A JSON Schema can also say what's allowed, and with From set to JSON Schema those rules become Field() arguments:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Signup",
"type": "object",
"required": ["email", "username", "plan", "seats"],
"properties": {
"email": { "type": "string", "format": "email" },
"username": { "type": "string", "minLength": 3, "maxLength": 20, "pattern": "^[a-z0-9_]+$" },
"plan": { "type": "string", "enum": ["free", "team", "enterprise"] },
"seats": { "type": "integer", "minimum": 1, "maximum": 500 },
"referralCode": { "type": ["string", "null"] },
"acceptedTermsOn": { "type": "string", "format": "date" }
}
} The schema's title names the model. minLength, maxLength and pattern become min_length, max_length and pattern; minimum and maximum become ge and le; the enum becomes a Literal. The email stays a plain str: Pydantic's EmailStr needs the separate email-validator package, so the converter doesn't assume you have it.
The converter's Python Pydantic output:
from __future__ import annotations
import datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
class Signup(BaseModel):
model_config = ConfigDict(populate_by_name=True)
email: str
username: str = Field(min_length=3, max_length=20, pattern="^[a-z0-9_]+$")
plan: Literal["free", "team", "enterprise"]
seats: int = Field(ge=1, le=500)
referral_code: Optional[str] = Field(default=None, alias="referralCode")
accepted_terms_on: Optional[datetime.date] = Field(default=None, alias="acceptedTermsOn")
Signup.model_rebuild() How JSON values become Python types
Strings become str, booleans bool, whole numbers int and numbers with a fraction float. Arrays become List[…], objects with no fixed keys Dict[str, …], and a UUID uuid.UUID. A field that is null in every sample is typed None, and a value of mixed kinds becomes a Union. A root that is an array becomes a RootModel.
Models come in an order where each follows the ones it uses, the file starts with from __future__ import annotations, and every model gets a model_rebuild() call at the end, so models that refer to each other, or to themselves, resolve.
Using the models
Parse a response with Root.model_validate_json(raw), or Root.model_validate(data) for a dict you already have. To send data back with the original keys, dump it with model_dump(by_alias=True); without by_alias, Pydantic writes the snake_case names.
Both examples on this page are among the converter's compile tests: Python imports each generated module and validates the samples above with Pydantic 2. Those checks run where Python and Pydantic are installed (the project's CI skips them); the TypeScript and Zod outputs of the same examples are checked in CI on every pull request.
5 common mistakes
- Dumping without
by_alias.model_dump()writesbooking_ref, notbookingRef, so an API that expects camelCase gets keys it doesn't know. Usemodel_dump(by_alias=True), ormodel_dump_json(by_alias=True). - Reading
Optionalas "may be left out".seat: Optional[str]with no default is required: the key must be there, though its value may beNone. Only fields with= Nonemay be missing. - Converting one record. Keys that aren't in your only sample aren't in the model, and keys that are null in it are typed
None. Paste several records in an array, or merge many samples into a schema in the JSON to Schema Generator and convert that. - Expecting validators to come across. A JSON example carries no rules, and a JSON Schema's
if/thenornothave noField()argument. Write those asfield_validatorormodel_validatormethods. - Expecting
EmailStr. Emails staystr. If you want Pydantic to check them, install email-validator and change the annotation toEmailStr.
Frequently Asked Questions
Does it write Pydantic v1 or v2 models?
Pydantic v2: ConfigDict, model_rebuild() and RootModel are v2 names. The annotations use typing's List and Optional, so the file runs on Python 3.9 and later.
Is my JSON uploaded?
No. The conversion runs in your browser. The site's usage log records which formats you converted between and a few counts, as the privacy policy describes.
Why is the top model called Root?
A JSON value has no name, so the converter calls the root Root and names nested models by their path, such as RootPassenger. A JSON Schema's title names the model instead, as Signup above.
Can I go from Pydantic to JSON Schema?
Pydantic does that itself: Model.model_json_schema(). The converter doesn't read Python, but that schema can go into the Schema Converter to become TypeScript, Zod or Go.
Other converters
- JSON to TypeScript Converter
- JSON to Go Struct Converter
- JSON Schema to Zod Converter
- Schema Converter, with every pair: JSON Schema, TypeScript, GraphQL or a JSON example in; TypeScript, Zod, Pydantic, Go, GraphQL or JSON Schema out
- JSON to Schema Generator, to infer a JSON Schema from one or more examples and refine it field by field