Home › JSON to Python

JSON to Python Converter Online

Generate Python dataclasses, TypedDict, or Pydantic models from JSON data instantly. Free online tool — no signup, your data stays in your browser.

Three Output Formats

Given this JSON:

{
  "id": 101,
  "name": "Alice Johnson",
  "email": "alice@example.com",
  "active": true,
  "score": 9.5
}

1. Python Dataclass

from dataclasses import dataclass

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

2. TypedDict

from typing import TypedDict

class Root(TypedDict):
    id: int
    name: str
    email: str
    active: bool
    score: float

3. Pydantic Model

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 to Python Type Mapping

JSON Type Python Type
stringstr
integer (42)int
float (3.14)float
booleanbool
nullNone / Optional[T]
array of stringslist[str]
array of objectslist[ChildClass]
objectNested class
mixed arraylist[str | int] (union)

Parse JSON into a Python Dataclass

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

Parse JSON with Pydantic (Validation)

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

Which Format Should I Use?

Format Best For
TypedDictType checking only, stays as dict, easiest JSON round-trip
DataclassStructured data with methods, no external dependencies
PydanticAPI validation, FastAPI, automatic JSON serialization, strict typing
Plain dictQuick scripts, prototyping, when structure doesn't matter

Frequently Asked Questions

How do I convert JSON to Python?+
Paste your JSON into the JSON to Python converter and click Convert. The tool generates Python dataclasses or typed dictionaries with correct type annotations matching your JSON structure. Copy the output directly into your Python project.
What Python type does JSON null map to?+
JSON 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].
Should I use dataclass or TypedDict for JSON data?+
Use 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.
How do I parse JSON in Python?+
Use the built-in 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).
Does the converter handle nested JSON objects?+
Yes. Each nested object generates a separate Python dataclass or TypedDict. The parent class references the child class by name. For example, a user with an address field generates both a User dataclass and an Address dataclass.
How do I serialize a Python object back to JSON?+
For regular dicts, use 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().

Generate Python code from your JSON

Free, instant — choose dataclass, TypedDict, or Pydantic.

JSON to Python Type Mapping

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 → Python Dataclass

# 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)

JSON → Pydantic Model (recommended for APIs)

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)

Python JSON Type Mappings

JSONPythonNotes
stringstr"hello"
integerint42
floatfloat3.14
booleanbooltrue → True
nullOptional[T] / Nonenull → None
arrayList[T][]
objectdict / dataclass{}

Working with JSON in Python: Complete Guide

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)

Python Dataclass from JSON

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"

Pydantic: Type-Safe JSON in Python

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