Skip to content
shellhacks.dev
Tooling

JSON to Python Class Generator

Generate Python dataclasses, Pydantic v2 models or TypedDicts from a JSON sample, with snake_case fields, aliases and Optional for nullable keys.

Free · No sign-up · Your inputs stay in your browser

Input

Generate Python types from JSON

Output

Python

411 characters

Field names are converted to snake_case. With Pydantic, a renamed field carries an alias so model_validate() still reads the original JSON key; dataclasses need the mapping done by hand. Optional fields default to None. Types come from this one sample: give fields that are null here a real value to type them.

Runs in this browser. Nothing you paste is sent to a server.

Which of the three to pick

A dataclass is standard library and does no validation. Pydantic validates and converts on the way in (Model.model_validate(data)) and is what FastAPI uses for request and response bodies. A TypedDict only describes a plain dict for type checkers such as mypy and Pyright, with no runtime cost at all, which suits code that already passes dicts around.

One sample is not a schema

A field that is always null in the sample cannot be typed beyond None; give it a real value. Numbers that happen to be whole in the sample become int, so a price of 5 would be typed int: check money fields and change them to Decimal by hand.

Share

Frequently asked questions

How do I map camelCase JSON keys to snake_case in Pydantic?
Give the field an alias: user_id: int = Field(alias="userId"). The generated models do this for every renamed key. Set model_config = ConfigDict(populate_by_name=True) if code should also be able to use the Python name.
Can I generate the classes from a JSON Schema instead of a sample?
Yes, with datamodel-code-generator, which reads JSON Schema and OpenAPI. A sample-based generator is quicker for an API that publishes no schema.
Is what I paste sent anywhere?
No. The tool runs entirely in your browser with JavaScript. Nothing you type or paste is sent to our server or stored.

Go deeper

Suggested reading

Keep planning

Similar tools