1001Ferramentas
🐍Converters

JSON to Python (dataclass)

Convert JSON to a Python dataclass with type hints. Supports List, Optional and nested classes. Everything in your browser.

JSON turned into typed dataclasses

You got a config file or an API payload as JSON and you would rather not sprinkle cfg.get('db').get('host') across the codebase. Typing the equivalent dataclass by hand is repetitive and it is easy to miss a nested field. Paste the JSON here, name the root class, and you get the code with @dataclass, the typing imports and the annotations ready to drop into your module.

Each nested object becomes its own class, named after the key in PascalCase, and it is written above the class that uses it. That ordering matters more than it looks: the file works read top to bottom, with no string annotations and no from __future__ import annotations. In lists only the first element is inspected, and the item class gets an Item suffix, so items becomes ItemsItem. A null value becomes Optional[Any].

The input has to be an object at the top level. An array or a bare value returns the message Esperado objeto, so wrap the list in a key first. Field names are copied verbatim, so keys like user-name or class produce invalid Python: rename them and map on read, or move to Pydantic with Field(alias=...). There is no copy button, select the box and hit Ctrl+C. It all runs in the browser.

Frequently asked questions

Does it output Pydantic models?
No, the output is a standard library dataclass. For Pydantic, swap the decorator for BaseModel inheritance and fix the imports; the field names and types still hold.
What if two keys share a name but have different fields?
The class is built once, from the first occurrence. If the two shapes differ, the second one comes out wrong. Rename one of the keys before converting.
Which Python version do I need?
3.7 or later, when dataclasses landed in the standard library. From 3.9 on you can replace List[str] with list[str] if you prefer the newer syntax.

Related Tools