PureDevTools

JSON to Pydantic Model Generator

Paste JSON, get Pydantic v2 (or v1) models — nested classes, Optional fields, Field aliases — copy or download as .py

All processing happens in your browser. No data is sent to any server.

Options

Version:

282 characters

2 classes generated · 482 characters

Classes generated: 2Pydantic version: v2Output size: 482 chars

You have a FastAPI endpoint, a LangChain agent output, or an API response — and you need a Pydantic model that matches it exactly. Writing BaseModel subclasses by hand for a 20-field JSON object with nested structures is tedious and error-prone. This tool reads your JSON and generates correct Pydantic v1 or v2 model definitions instantly, with proper type annotations, Field aliases for camelCase keys, and Optional handling for nullable fields.

What Is Pydantic?

Pydantic is a Python data validation library that uses Python type annotations to validate and parse data at runtime. You define a class that extends BaseModel, declare fields with their types, and Pydantic handles the rest: type coercion, validation, serialization, and detailed error messages when data doesn’t match.

Pydantic is the most downloaded Python library in its category and is the backbone of:

Pydantic v1 vs v2

Pydantic v2 (released June 2023) is a complete rewrite in Rust. It is 10–50x faster than v1 and introduces breaking changes in the API.

FeaturePydantic v1Pydantic v2
List annotationList[str] from typinglist[str] built-in
Validator decorator@validator@field_validator
Model configclass Config:model_config = ConfigDict(...)
Serialization.dict().model_dump()
JSON export.json().model_dump_json()
PerformanceBaseline10-50x faster

This tool generates the correct syntax for whichever version you select. If you are starting a new project, use Pydantic v2. If you are maintaining a legacy codebase, use v1.

camelCase to snake_case Conversion

Python convention is snake_case for field names, but JSON APIs — especially those built with JavaScript/TypeScript — use camelCase. This tool automatically converts JSON keys:

When Field() aliases is enabled, the tool generates Field(..., alias="firstName") so Pydantic accepts the original camelCase key when parsing JSON, while your Python code uses the Pythonic first_name name:

from pydantic import BaseModel, Field

class User(BaseModel):
    first_name: str = Field(..., alias="firstName")
    is_active: bool = Field(..., alias="isActive")
    user_id: int = Field(..., alias="userId")

To parse JSON with aliases in Pydantic v2, pass model_validate with by_alias=True, or configure model_config = ConfigDict(populate_by_name=True) on the model.

Nested Models

When your JSON contains nested objects, each nested object becomes its own BaseModel subclass. Nested classes are emitted before the classes that reference them, so no forward references are needed:

class UserAddress(BaseModel):
    street: str
    city: str
    zip_code: str = Field(..., alias="zipCode")

class User(BaseModel):
    id: int
    name: str
    address: UserAddress

Optional Fields and Nullable Values

When Optional[] for nulls is enabled (the default), JSON fields with null values are annotated as Optional[Any] = None. This is the correct Python pattern for fields that may be absent or null:

from typing import Optional, Any

class User(BaseModel):
    name: str
    deleted_at: Optional[Any] = None

In Pydantic v2, you can also use str | None syntax instead of Optional[str] — this tool uses Optional for broader compatibility, but either form is accepted.

Validator Examples

When validator example is enabled, the tool generates a @field_validator (v2) or @validator (v1) stub for the first string field in each class. This shows you where to add custom validation logic:

from pydantic import BaseModel, field_validator

class User(BaseModel):
    name: str

    @field_validator("name")
    @classmethod
    def validate_name(cls, v: str) -> str:
        if not v.strip():
            raise ValueError("name must not be blank")
        return v.strip()

How to Use

  1. Paste your JSON in the JSON Input panel (or click Load sample)
  2. Set the Root class name to match your domain (e.g., User, Order, Product)
  3. Select your Pydantic version (v2 for new projects, v1 for legacy)
  4. Enable Optional[] for nulls to handle nullable fields correctly
  5. Enable Field() aliases if your JSON uses camelCase keys
  6. Copy the output or Download .py to save as a file

Common Use Cases

FastAPI request body: Generate the Pydantic model for a request body directly from a sample payload captured in Postman or curl.

LangChain structured output: When using with_structured_output(), the output schema is a Pydantic model. Generate it from a sample LLM response.

Webhook handling: External services send webhook payloads in fixed shapes. Generate a Pydantic model from the webhook sample in the service’s documentation.

Configuration files: If your app reads a JSON config file, generate a Pydantic settings model. Combine with pydantic-settings for environment variable support.

FAQ

Does this tool send my JSON to a server?

No. All processing runs entirely in your browser using JavaScript. Your JSON never leaves your device.

What Python version do the generated models require?

Pydantic v2 models use built-in list[T] syntax which requires Python 3.9+. Pydantic v1 models use List[T] from typing which works from Python 3.7+. Pydantic v2 itself requires Python 3.8+.

How are arrays of objects handled?

If a JSON array contains objects, the tool merges all objects in the array into a single model class. Fields present in only some of the objects become Optional[T] = None.

Can I use these models with FastAPI directly?

Yes. FastAPI uses Pydantic models natively. Import the generated class and use it as a type hint for your path operation function parameter:

from fastapi import FastAPI
from .models import User  # generated model

app = FastAPI()

@app.post("/users")
def create_user(user: User):
    return user.model_dump()

What if my JSON root is an array?

The tool generates a model for the array element type, named after your root class. Use it as list[Root] in your application code.

How do I handle fields that can be multiple types (union types)?

The tool infers types from the actual data provided. If a field contains a string in your sample but can also be null, enable Optional[] for nulls. For genuine union types (str | int), manually edit the generated annotation after copying.

Related Tools

More JSON Tools