JSON to Python
Generate Python classes from any JSON object. Choose between @dataclass, TypedDict, or Pydantic v2 BaseModel.
stdlib @dataclass — no dependencies
Which Python type should I use?
| dataclass | TypedDict | Pydantic v2 | |
|---|---|---|---|
| Runtime validation | No | No | Yes — raises ValidationError |
| Dependencies | stdlib | stdlib | pip install pydantic |
| Mutation | Yes (mutable) | Yes | Optional (frozen=True) |
| JSON serialization | Manual / json.dumps | Manual | model.model_dump_json() |
| Field defaults | field(default=…) | Not required keys | Field(default=…) |
| ORM integration | No | No | Yes (SQLModel, etc.) |
| Best for | Data pipelines, dataclasses | Type hints only, dicts | APIs, validation, serialization |
Pydantic v2 — Parse and Validate JSON
python
from pydantic import BaseModel
from typing import Any
class Address(BaseModel):
city: str
country: str
model_config = {"extra": "forbid"}
class Root(BaseModel):
name: str
email: str
age: int
active: bool
tags: list[str]
address: Address
model_config = {"extra": "forbid"}
import json
# Parse from JSON string
data = json.loads('{"name":"Ravi","email":"ravi@example.com","age":28,"active":true,"tags":["dev"],"address":{"city":"Surat","country":"IN"}}')
obj = Root.model_validate(data)
print(obj.name) # => Ravi
print(obj.address.city) # => Surat
# Serialize back to JSON
print(obj.model_dump_json(indent=2))@dataclass — Lightweight, No Dependencies
python
from __future__ import annotations
from dataclasses import dataclass
import json
from typing import Any
@dataclass
class Address:
city: str
country: str
@dataclass
class Root:
name: str
email: str
age: int
active: bool
tags: list[str]
address: Address
# Instantiate directly
addr = Address(city="Surat", country="IN")
user = Root(name="Ravi", email="ravi@example.com", age=28,
active=True, tags=["dev"], address=addr)
print(user.name) # => Ravi
print(user.address.city) # => Surat
# Note: dataclasses don't auto-parse from dict.
# Use dacite for dict-to-dataclass mapping:
# pip install dacite
from dacite import from_dict
user2 = from_dict(Root, data_dict)