Just Formatter

JSON to Pydantic Model Generator

Paste any JSON and generate Pydantic models with full type annotations instantly in your browser — no signup, nothing uploaded.

JSON Input

Pydantic Models

How to Generate Pydantic Models from JSON

1

Paste your JSON

Copy a JSON response, config file, or any JSON object and paste it into the input panel. Minified or pretty-printed JSON both work.

2

Set a model name

Enter a name for the top-level model class. Defaults to Root. Use something descriptive like User, ApiResponse, or OrderPayload.

3

Generate and copy

Click Generate Models. Copy the output or download it as a .py file with all imports included and ready to use.

What Is Pydantic?

Pydantic is a Python library for data validation using type annotations. You define a model by subclassing BaseModel and annotating each field. When you create an instance, Pydantic validates and coerces the input to match the declared types.

Pydantic is the validation layer behind FastAPI and is widely used for config management, ETL pipelines, and API client libraries. It provides automatic JSON serialization via model.model_dump_json() and deserialization via Model.model_validate(data).

Example

from __future__ import annotations
from pydantic import BaseModel


class User(BaseModel):
    id: int
    name: str
    email: str
    address: Address


class Address(BaseModel):
    street: str
    city: str
    zip: str

How the Generator Works

Type inference

JSON strings map to str, integers to int, decimals to float, booleans to bool, and null to Optional[Any].

Nested models

Each nested JSON object generates its own named BaseModel class. The class name is derived from the JSON key in PascalCase. from __future__ import annotations enables forward references so classes can reference each other regardless of order.

Arrays of objects

When an array contains objects, all elements are merged into a single model. Keys present in only some elements get type Optional[T] = None. This handles APIs that omit fields instead of returning them as null.

Imports are generated automatically

Optional and Any from typing are only included if the generated models actually use them — no unused imports.

Use Cases

FastAPI Request & Response Models

Generate Pydantic models from your API contract or example payloads. Use them directly as FastAPI request body types and response_model declarations.

Data Validation Pipelines

Parse and validate JSON from external data sources — files, APIs, message queues — using Pydantic model_validate(). Any field type mismatch raises a ValidationError at the boundary.

Config File Schemas

Convert a JSON config file into a Pydantic Settings model. Get type-safe access to config values with automatic casting from environment variables and JSON files.

LLM Output Parsing

Define the expected shape of structured outputs from language models using Pydantic. Libraries like instructor and LangChain use Pydantic models to enforce JSON output schemas.

ETL Schema Documentation

Generate models from sample records in your data pipeline to serve as living documentation of the schema. Pydantic validation catches schema drift between pipeline stages.

Third-Party API Integration

Paste a JSON response from an external API to generate the Pydantic model for it. Use model_validate() instead of accessing dict keys directly for type-safe deserialization.

Generated Model Examples

Simple flat object

JSON input

{
  "id": 42,
  "name": "Alice",
  "active": true
}

Pydantic output

from __future__ import annotations
from pydantic import BaseModel


class Root(BaseModel):
    id: int
    name: str
    active: bool

Array with optional fields

JSON input

[
  {"id":1,"name":"Alice","role":"admin"},
  {"id":2,"name":"Bob"}
]

Pydantic output

# Top-level JSON is an array: list[Root]

from __future__ import annotations
from typing import Optional
from pydantic import BaseModel


class Root(BaseModel):
    id: int
    name: str
    role: Optional[str] = None

Nullable field and nested model

JSON input

{
  "id": 1,
  "address": {"city": "NY"},
  "metadata": null
}

Pydantic output

from __future__ import annotations
from typing import Any, Optional
from pydantic import BaseModel


class Root(BaseModel):
    id: int
    address: Address
    metadata: Optional[Any] = None


class Address(BaseModel):
    city: str

Pydantic v1 vs v2 Compatibility

The generated models use BaseModel and standard Optional/Any annotations, which are compatible with both Pydantic v1 and v2.

  • v1 usage: Parse with Root.parse_obj(data) and serialize with instance.json().
  • v2 usage: Parse with Root.model_validate(data) and serialize with instance.model_dump_json().
  • Python 3.10+ alternative: Replace Optional[T] with T | None if your codebase uses the newer union syntax.

Limitations to Be Aware Of

  • Null fields: A JSON null cannot reveal its real type, so it becomes Optional[Any]. Change to Optional[str] or the real type if known.
  • Field names kept as-is: JSON keys are used as Python attribute names without snake_case conversion. If your JSON uses camelCase (firstName), the field will be firstName: str. Add model_config = ConfigDict(alias_generator=to_camel) if you want snake_case attributes.
  • Single sample inference: Types are inferred from the values you provide. If a field is sometimes a string and sometimes null, provide an example with both to see the union, or manually add Optional[str].
  • No validator decorators: The generator produces basic type annotations only. Add @field_validator or Field() constraints manually where you need value validation beyond type checking.

Frequently Asked Questions

How do I convert JSON to a Pydantic model?

Paste your JSON into the input box, optionally set a root model name, and click Generate Models. The tool produces Pydantic BaseModel class definitions with type annotations that match the exact shape of your JSON, ready to use with Pydantic v1 or v2.

What is Pydantic and why should I use it?

Pydantic is a Python data validation library that uses type annotations to validate and serialize data at runtime. It is the foundation of FastAPI and widely used for config parsing, API models, and ETL pipelines. Defining Pydantic models gives you automatic validation, IDE autocomplete, and JSON serialization out of the box.

How are optional and nullable fields handled?

Fields that are null in the JSON get type Optional[Any] = None. Fields that appear in only some elements of an array are marked Optional[T] = None, where T is inferred from the elements where the field is present.

Does the generated code work with Pydantic v2?

Yes. The output uses standard Python type annotations and BaseModel, which are compatible with both Pydantic v1 and v2. In Pydantic v2, Optional[T] is equivalent to T | None and behaves identically.

How are nested objects handled?

Each nested JSON object becomes a separate Pydantic model class named in PascalCase from the JSON key. The from __future__ import annotations at the top enables forward references so class order does not matter.

Is my JSON sent to a server?

No. All model generation runs entirely in your browser using JavaScript. Your JSON data never leaves your device and is not stored anywhere.

Can I use the generated models with FastAPI?

Yes. FastAPI uses Pydantic models for request and response body validation. Paste the generated models into your FastAPI app and use them as request body types (def create_user(user: User): ...) or response models (response_model=User).

From the Blog

View all →

Related Tools