JSON to Python Dataclass

Infer Python dataclasses from a JSON sample.

About JSON to Python Dataclass

Generate Python dataclasses from a JSON sample. Paste JSON and typed @dataclass definitions appear as you type, one class per nested object, dates recognised.

How to use

  1. Paste JSON, or load a .json file (up to 5 MB).
  2. Optionally change the root class name (default Root). It must start with a letter or underscore and contain only letters, digits and underscores, up to 64 characters.
  3. The Python code updates as you type. Copy it, or Download it as a .py file.

Inference rules

  • Integers become int, other numbers float, booleans bool, strings str, and null becomes Optional[Any].
  • A string matching YYYY-MM-DD becomes date; an ISO 8601 timestamp such as 2024-01-31T09:00:00Z becomes datetime.
  • A list becomes List[T]. Mixed element types produce List[Union[...]], except that int and float together collapse to List[float]. An empty list is List[Any].
  • A nested object becomes its own class named after its path, for example RootAddress or RootUserAddress, listed before the class that uses it. An empty object becomes a class with pass.
  • A list of objects is typed from all its items: a key missing from some items becomes Optional[T] = None and is listed after the required fields.
  • The header imports only what the classes use.
  • A key that is not a valid Python identifier is renamed to snake_case (first-name → first_name, class → class_) with the original key in a comment.

Example

{ "id": 1, "name": "Ada", "joined": "2024-01-31" }
→
from dataclasses import dataclass
from datetime import date

@dataclass
class Root:
    id: int
    name: str
    joined: date

Privacy

Inference runs in the page. No request is made and nothing is stored.

Frequently asked questions

What is a Python dataclass?
A class decorated with @dataclass from the standard library (Python 3.7 and later). The decorator generates __init__, __repr__ and __eq__ from the annotated fields, so a dataclass is a concise way to hold structured data.
Does a dataclass validate the types of its fields?
No. The annotations are hints for type checkers and editors; at runtime a dataclass accepts any value. Use Pydantic or a manual check if you need validation when loading JSON.
How do I load JSON into a dataclass?
Parse the JSON with json.loads and unpack the dict with Root(**data). Nested objects and date strings are not converted automatically, so convert them first or use a library such as dacite or Pydantic.
Why is a JSON null typed as Optional[Any]?
A single null value gives no information about the real type, so the generator writes Optional[Any] as a placeholder. Replace Any with the real type once you know what the field holds; a sample where the field is set in another item already gets Optional[T].