Use JSON to Python Class

Enter your data below to use the JSON to Python Class

📌 Try these examples:
RESULT

Last updated

Example: Nested Objects

// Input JSON:
{
  "user": {
    "id": 1,
    "name": "Alice",
    "address": {
      "street": "123 Main St",
      "city": "New York",
      "zip": "10001"
    }
  }
}

# Generated Python dataclasses:
from dataclasses import dataclass

@dataclass
class Address:
    street: str
    city: str
    zip: str

@dataclass
class User:
    id: int
    name: str
    address: Address

@dataclass
class Root:
    user: User

# Usage:
data = {"user": {"id": 1, "name": "Alice", "address": {"street": "123 Main St", "city": "New York", "zip": "10001"}}}
root = Root(user=User(id=data['user']['id'], name=data['user']['name'], address=Address(**data['user']['address'])))
print(root.user.address.city)  # → New York

Example: Arrays and Optional Fields

// Input JSON:
{
  "id": 1,
  "username": "alice",
  "email": "alice@example.com",
  "bio": null,
  "roles": ["admin", "editor"],
  "scores": [85, 92, 78]
}

# Generated Python dataclass:
from dataclasses import dataclass, field
from typing import List, Optional

@dataclass
class Root:
    id: int
    username: str
    email: str
    bio: Optional[str]
    roles: List[str]
    scores: List[int]

Example: Pydantic Model

// Input JSON:
{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com",
  "age": 30,
  "active": true
}

# Generated Pydantic model:
from pydantic import BaseModel
from typing import Optional

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int
    active: bool

# Usage with FastAPI:
from fastapi import FastAPI

app = FastAPI()

@app.post("/users")
async def create_user(user: User):
    return {"message": f"Created user {user.name}"}

# Pydantic validates automatically:
user = User(id=1, name="Alice", email="alice@example.com", age=30, active=True)
user = User(id="not-an-int", ...)  # → ValidationError: id must be int

Example: Complex API Response

// Input JSON:
{
  "status": "success",
  "data": {
    "users": [
      { "id": 1, "name": "Alice", "role": "admin" },
      { "id": 2, "name": "Bob",   "role": "user" }
    ],
    "pagination": {
      "page": 1,
      "perPage": 20,
      "total": 150
    }
  }
}

# Generated Python dataclasses:
from dataclasses import dataclass
from typing import List

@dataclass
class UserItem:
    id: int
    name: str
    role: str

@dataclass
class Pagination:
    page: int
    per_page: int  # camelCase → snake_case
    total: int

@dataclass
class Data:
    users: List[UserItem]
    pagination: Pagination

@dataclass
class ApiResponse:
    status: str
    data: Data

Example: from_dict and to_dict Methods

# Generated with serialization methods:
from dataclasses import dataclass, asdict
from typing import Optional

@dataclass
class User:
    id: int
    name: str
    email: str
    bio: Optional[str] = None

    @classmethod
    def from_dict(cls, data: dict) -> 'User':
        return cls(
            id=data['id'],
            name=data['name'],
            email=data['email'],
            bio=data.get('bio')
        )

    def to_dict(self) -> dict:
        return asdict(self)

# Usage:
import json

json_str = '{"id": 1, "name": "Alice", "email": "alice@example.com"}'
user = User.from_dict(json.loads(json_str))
print(user.name)  # → Alice

back_to_json = json.dumps(user.to_dict())

Example: Inheritance for Shared Fields

// Input JSON (multiple types with shared fields):
// Article: { "id": 1, "createdAt": "...", "title": "...", "content": "..." }
// Comment: { "id": 2, "createdAt": "...", "text": "...", "authorId": 1 }

# Generated with base class:
from dataclasses import dataclass
from datetime import datetime

@dataclass
class BaseModel:
    id: int
    created_at: str  # ISO 8601 datetime string

@dataclass
class Article(BaseModel):
    title: str
    content: str

@dataclass
class Comment(BaseModel):
    text: str
    author_id: int

camelCase to snake_case Mapping

// JSON uses camelCase:
{
  "userId": 1,
  "firstName": "Alice",
  "lastName": "Smith",
  "createdAt": "2024-01-15",
  "isActive": true
}

# Python uses snake_case:
@dataclass
class User:
    user_id: int       # userId → user_id
    first_name: str    # firstName → first_name
    last_name: str     # lastName → last_name
    created_at: str    # createdAt → created_at
    is_active: bool    # isActive → is_active

# Pydantic handles the mapping automatically:
class User(BaseModel):
    user_id: int
    first_name: str
    last_name: str
    created_at: str
    is_active: bool

    class Config:
        alias_generator = lambda s: ''.join(
            w.capitalize() if i else w
            for i, w in enumerate(s.split('_'))
        )
        populate_by_name = True

Paste your JSON to generate Python dataclasses or Pydantic models instantly. Choose between dataclass output for standard Python and Pydantic output for FastAPI and data validation use cases.

Example: Simple Object → Dataclass

// Input JSON:
{
  "id": 42,
  "name": "Alice Smith",
  "email": "alice@example.com",
  "age": 30,
  "active": true,
  "score": 98.5
}

# Generated Python dataclass:
from dataclasses import dataclass
from typing import Optional

@dataclass
class Root:
    id: int
    name: str
    email: str
    age: int
    active: bool
    score: float

Frequently Asked Questions

Simply enter your data, click the process button, and get instant results. All processing happens in your browser for maximum privacy and security.

Yes! JSON to Python Class is completely free to use with no registration required. All processing is done client-side in your browser.

Absolutely! All processing happens locally in your browser. Your data never leaves your device, ensuring complete privacy and security.