JSON to Python dataclass

The tool writes a dataclass per object, ordered so each class is defined before it is used, and keeps valid key names as they are.

Loading the tool…

Processing and privacy: The result is calculated inside your browser and your data is not sent to any server.

How to use it

  1. Enter json input and root type name.
  2. The result appears straight away and updates as you edit.
  3. Copy the result, or copy a link that keeps the same values to share it.

How it is calculated

str, int, float, bool, List[T] and Any, with a dataclass per nested object. null makes the type Optional[T], and a key missing from some items gets a default of None and moves to the end of the class, because Python requires fields with defaults to come last.

Example

Inputs: Root type name = Root. Result: Generated code: from dataclasses import dataclass from typing import List, Optional @dataclass class Order: order_id: str total: float coupon: Optional[str] @dataclass class Address: city: str postal_code: str @dataclass class Root: id: int name: str email: str is_active: bool balance: float tags: List[str] address: Address orders: List[Order]; Types generated: 3; Fields: 13.

{
  "id": 1024,
  "name": "Sara Ahmed",
  "email": "sara@example.com",
  "is_active": true,
  "balance": 1520.75,
  "tags": ["vip", "riyadh"],
  "address": { "city": "Riyadh", "postal_code": "12211" },
  "orders": [
    { "order_id": "A-1", "total": 99.5, "coupon": "EID10" },
    { "order_id": "A-2", "total": 120, "coupon": null }
  ]
}
from dataclasses import dataclass
from typing import List, Optional


@dataclass
class Order:
    order_id: str
    total: float
    coupon: Optional[str]


@dataclass
class Address:
    city: str
    postal_code: str


@dataclass
class Root:
    id: int
    name: str
    email: str
    is_active: bool
    balance: float
    tags: List[str]
    address: Address
    orders: List[Order]

Limits and caveats

  • Root(**data) does not turn nested dicts into classes, so build them yourself or use a library such as dacite.
  • A key that is not a valid Python name becomes snake_case, with a comment showing the original key.

Questions about this tool

Why did some fields move to the end?

Fields with a default of None must follow the required ones, otherwise Python rejects the class definition.

Which Python version do I need?

Python 3.7 or newer, the release that added dataclasses to the standard library.

Is my JSON sent to a server?

No. The conversion runs in your browser and the JSON never leaves your device.