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
- Paste JSON, or load a
.jsonfile (up to 5 MB). - 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. - The Python code updates as you type. Copy it, or Download it as a
.pyfile.
Inference rules
- Integers become
int, other numbersfloat, booleansbool, stringsstr, andnullbecomesOptional[Any]. - A string matching
YYYY-MM-DDbecomesdate; an ISO 8601 timestamp such as2024-01-31T09:00:00Zbecomesdatetime. - A list becomes
List[T]. Mixed element types produceList[Union[...]], except thatintandfloattogether collapse toList[float]. An empty list isList[Any]. - A nested object becomes its own class named after its path, for example
RootAddressorRootUserAddress, listed before the class that uses it. An empty object becomes a class withpass. - A list of objects is typed from all its items: a key missing from some items becomes
Optional[T] = Noneand 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].