Generate Python dataclasses, TypedDict, or Pydantic models from JSON data instantly. Free online tool — no signup, your data stays in your browser.
Given this JSON:
{
"id": 101,
"name": "Alice Johnson",
"email": "alice@example.com",
"active": true,
"score": 9.5
}
from dataclasses import dataclass
@dataclass
class Root:
id: int
name: str
email: str
active: bool
score: float
from typing import TypedDict
class Root(TypedDict):
id: int
name: str
email: str
active: bool
score: float
from pydantic import BaseModel
class Root(BaseModel):
id: int
name: str
email: str
active: bool
score: float
# Usage:
user = Root.model_validate(json_dict)
print(user.name) # "Alice Johnson"
print(user.model_dump_json()) # Back to JSON
| JSON Type | Python Type |
|---|---|
string | str |
integer (42) | int |
float (3.14) | float |
boolean | bool |
null | None / Optional[T] |
| array of strings | list[str] |
| array of objects | list[ChildClass] |
| object | Nested class |
| mixed array | list[str | int] (union) |
import json
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
email: str
active: bool
def from_json(json_str: str) -> User:
data = json.loads(json_str)
return User(**data)
user = from_json('{"id":1,"name":"Alice","email":"a@b.com","active":true}')
print(user.name) # Alice
from pydantic import BaseModel, EmailStr, ValidationError
class User(BaseModel):
id: int
name: str
email: EmailStr
active: bool = True # default value
# Valid JSON
user = User.model_validate_json('{"id":1,"name":"Alice","email":"alice@example.com"}')
print(user.id) # 1
print(user.email) # alice@example.com
# Invalid JSON — Pydantic raises ValidationError with clear messages
try:
User.model_validate_json('{"id":"not-a-number","name":"Alice"}')
except ValidationError as e:
print(e) # id: Input should be a valid integer
| Format | Best For |
|---|---|
| TypedDict | Type checking only, stays as dict, easiest JSON round-trip |
| Dataclass | Structured data with methods, no external dependencies |
| Pydantic | API validation, FastAPI, automatic JSON serialization, strict typing |
| Plain dict | Quick scripts, prototyping, when structure doesn't matter |
null maps to Python None. In type annotations, a nullable field is typed as Optional[str] (or str | None in Python 3.10+). Fields that are always null in the sample data are typed as Optional[Any].dataclass when you want an actual class with methods and a constructor. Use TypedDict when you only need type annotations for dicts (no instance creation, useful with mypy). For simple API response typing, TypedDict is lighter-weight.json module: json.loads(json_string) for strings, or json.load(file_obj) for files. For type-safe validation and parsing, use Pydantic: from pydantic import BaseModel; user = User.model_validate_json(json_str).User dataclass and an Address dataclass.json.dumps(data). For dataclasses, use json.dumps(dataclasses.asdict(obj)). For Pydantic models, use model.model_dump_json(). For custom objects, pass a custom default serializer function to json.dumps().Free, instant — choose dataclass, TypedDict, or Pydantic.
Python's typing module, dataclasses, and Pydantic all provide ways to work with typed JSON data. Choose the right approach based on your validation needs.
# JSON Input
# {"id": 1, "name": "Alice", "active": true, "score": 98.5, "tags": ["admin"]}
from dataclasses import dataclass
from typing import List
import json
@dataclass
class User:
id: int
name: str
active: bool
score: float
tags: List[str]
# Deserialize
data = json.loads(json_string)
user = User(**data)
from pydantic import BaseModel
from typing import List
class User(BaseModel):
id: int
name: str
active: bool
score: float
tags: List[str]
# Auto-validates on creation
user = User.model_validate_json(json_string)
print(user.name) # "Alice"
# Re-serialize
json_out = user.model_dump_json(indent=2)
| JSON | Python | Notes |
|---|---|---|
| string | str | "hello" |
| integer | int | 42 |
| float | float | 3.14 |
| boolean | bool | true → True |
| null | Optional[T] / None | null → None |
| array | List[T] | [] |
| object | dict / dataclass | {} |
import json
# Parse JSON string to Python
data = json.loads('{"name": "Alice", "age": 30}')
print(data['name']) # "Alice"
print(type(data)) # <class 'dict'>
# Parse JSON from file
with open('data.json', 'r') as f:
data = json.load(f)
# Serialize Python to JSON string
json_str = json.dumps(data)
json_pretty = json.dumps(data, indent=2, sort_keys=True)
# Write JSON to file
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
# Handle special types
from datetime import datetime
import json
def json_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f'Object of type {type(obj)} is not JSON serializable')
json.dumps({'date': datetime.now()}, default=json_serializer)
from dataclasses import dataclass, field
from typing import Optional, List
import json
@dataclass
class Address:
city: str
country: str
@dataclass
class User:
name: str
age: int
email: str
address: Address
tags: List[str] = field(default_factory=list)
active: bool = True
score: Optional[float] = None
# Manual parsing into dataclass
def parse_user(data: dict) -> User:
return User(
name=data['name'],
age=data['age'],
email=data['email'],
address=Address(**data['address']),
tags=data.get('tags', []),
active=data.get('active', True),
score=data.get('score')
)
data = json.loads(json_string)
user = parse_user(data)
print(user.name) # "Alice"
from pydantic import BaseModel, EmailStr
from typing import Optional, List
class Address(BaseModel):
city: str
country: str
class User(BaseModel):
name: str
age: int
email: EmailStr # validates email format
address: Address
tags: List[str] = []
active: bool = True
score: Optional[float] = None
# Parse and validate JSON
user = User.model_validate_json(json_string)
print(user.name)
# Serialize back to JSON
json_output = user.model_dump_json(indent=2)
Also useful: JSON to TypeScript | JSON to Java | JSON Schema Tutorial | JSON Validator | Validate JSON