Skip to content

JSON to Python Dataclass

Convert JSON data to Python dataclass definitions with proper type annotations and imports

From API Response to Typed Python in Seconds

You’re building a Python client for a REST API that returns deeply nested JSON. You could define the dataclasses manually — field by field, type annotation by type annotation, import statement by import statement. Or you could paste the JSON response and get production-ready @dataclass definitions with all the types mapped correctly.

The tool handles the tedious parts: str, int, float, bool mapping, Optional for nullable fields, List[Type] for arrays, nested dataclasses for nested objects, and the from dataclasses import dataclass and from typing import Optional, List imports at the top.

What You Get

Paste {"name": "John", "age": 30, "active": true, "address": {"city": "NYC"}} and get:

from dataclasses import dataclass
from typing import Optional, List

@dataclass
class Address:
    city: str

@dataclass
class Root:
    name: str
    age: int
    active: bool
    address: Address

Nested objects produce separate dataclasses. Arrays become List[Type]. Null values become Optional[str]. Everything’s properly indented and ready to paste.

Practical Applications

FastAPI development. You’ve got a JSON payload from a client and need to define your request/response models. Generate the dataclasses here, then convert them to Pydantic models by swapping @dataclass for class Root(BaseModel): and changing the imports. The type annotations already work with Pydantic.

API client libraries. You’re wrapping a third-party API in Python. Paste a sample response, generate the dataclasses, and use them to deserialize API responses with dacite or dataclasses-json.

Data pipelines. Your ETL script processes JSON data from various sources. Define typed containers for the data instead of passing around raw dictionaries. Catch type errors early instead of debugging KeyError exceptions in production.

Configuration files. Your app reads a config.json. Generate a dataclass from it, and your IDE gives you autocomplete and type checking on every config field.

Refining the Output

The generated code is a starting point. Consider adding:

  • Default values for optional fields (city: str = "")
  • A __post_init__ method for validation
  • field(default_factory=list) for list fields
  • Conversion to Pydantic BaseModel for runtime validation and JSON serialization

For TypeScript interfaces from the same JSON, the JSON to TypeScript tool is available. For Go structs, use the JSON to Go Struct converter. Useful when your team works across multiple languages.

All conversion runs in your browser. Your data doesn’t leave the page.

json python dataclass types converter

Related Tools

More in Data Tools