Convert JSON to a Pydantic BaseModel in Python

Learn how to convert JSON to Pydantic BaseModel classes with automatic validation, serialization, and type coercion. Covers Pydantic v2 syntax and features.

Pydantic & TypedDict

Detailed Explanation

JSON to Pydantic BaseModel

Pydantic is the most popular data validation library in Python. It provides runtime validation, automatic type coercion, and JSON serialization out of the box.

Example JSON

{
  "id": 42,
  "name": "Alice",
  "email": "alice@example.com",
  "age": 30,
  "is_active": true,
  "tags": ["admin", "developer"]
}

Generated Python (Pydantic v2)

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int
    is_active: bool
    tags: list[str]

Key Differences from Dataclasses

Feature dataclass Pydantic BaseModel
Validation None (type hints only) Runtime validation
Type coercion No Yes ("42" -> 42)
JSON serialization Manual .model_dump_json()
JSON deserialization Manual .model_validate_json()
Performance Faster construction Validation overhead

Usage

import json

# From dict
user = User(**json.loads(raw_json))

# Or directly from JSON string (Pydantic v2)
user = User.model_validate_json(raw_json)

# Serialize back to JSON
json_str = user.model_dump_json()

# To dict
data = user.model_dump()

Validation in Action

# This raises ValidationError — age must be int
User(id=1, name="Alice", email="a@b.com", age="not a number", is_active=True, tags=[])

# This works — Pydantic coerces "42" to 42
User(id=1, name="Alice", email="a@b.com", age="42", is_active=True, tags=[])

Field Constraints

Pydantic lets you add validation constraints:

from pydantic import BaseModel, Field

class User(BaseModel):
    id: int = Field(gt=0)
    name: str = Field(min_length=1, max_length=100)
    email: str
    age: int = Field(ge=0, le=150)

When to Choose Pydantic over Dataclasses

  • You need runtime validation (API inputs, form data, config files).
  • You want automatic JSON serialization/deserialization.
  • You are using FastAPI (which requires Pydantic models).
  • You need type coercion (strings to numbers, etc.).

Use Case

You are building a FastAPI application and need request/response models that automatically validate incoming JSON payloads, coerce types, and generate OpenAPI documentation.

Try It — JSON to Python Converter

Open full tool