1. Home
  2. Developer tools
  3. JSON to Pydantic & dataclass

JSON to Pydantic & dataclass

Validate API data in FastAPI or any Python project without typing models by hand: paste JSON and copy ready-made Pydantic or dataclass definitions.

Free, no sign-up. Runs in your browser: nothing is uploaded.

How to use JSON to Pydantic & dataclass

  1. Paste JSON.
  2. Choose Pydantic v2 or dataclasses.
  3. Copy the module into your project.

Features

  • Classes ordered so each is defined before it is used
  • snake_case attributes with Field(alias=…) and populate_by_name
  • Optional fields typed T | None = None and placed after required ones
  • list[T], int, float, bool, str and Any
  • Optional datetime and date for ISO strings

Supported formats

You can open

  • JSON
  • JSON Lines
  • Typed or pasted text

You get

  • PY
  • Copied text

Private by design

Your files are opened and processed by your browser on this device. They are never uploaded to openWorkstand or anyone else, so the JSON to Pydantic & dataclass is safe for contracts, IDs, photos and work documents. After you have used it once while online, it also works without an internet connection. How local processing works

Good to know

  • Types are inferred from the samples given; paste several varied samples for accurate optional fields.

Guide

Pydantic v2 models and dataclasses from JSON

Python code that consumes JSON usually ends up with dictionaries everywhere and KeyError surprises. Modelling the data with Pydantic or dataclasses gives you attribute access, editor completion and, with Pydantic, validation at the boundary. This generator writes those models from a sample, including the awkward parts: keys that are not valid Python names, optional fields and nested lists.

Pydantic or dataclasses

Choose Pydantic v2 when the data comes from outside — an API, a webhook, a user upload. User.model_validate(data) checks every field, converts compatible values (the string “5” to an int, an ISO string to a datetime) and raises a clear error listing every problem. Choose dataclasses for internal data or scripts where you want no dependency; they give structure and type hints but do no checking at runtime.

Names and aliases

Python attributes are snake_case, so userName becomes user_name and content-type becomes content_type. Python keywords and common builtins such as class, type, id and list get a trailing underscore. In Pydantic, any attribute whose name differs from the key gets Field(alias="…"), and the class enables populate_by_name, so you can build instances in Python with the attribute names while JSON still uses the original keys. Dataclasses have no alias mechanism, so a comment records the key.

Optional fields and ordering

A key missing from any sample becomes T | None = None. Values that are null but always present are typed T | None without a default. Fields with defaults are placed after required ones, which dataclasses require and which keeps Pydantic models easy to read. The from __future__ import annotations line lets the X | None syntax work on Python 3.8 and 3.9 and lets classes refer to each other in any order.

Dates and loose values

With date types on, ISO 8601 timestamps become datetime and plain dates date; Pydantic parses them for you. Values that were always null or changed type become Any, imported only when used.

Using the models in FastAPI

Declare a model as a parameter type and FastAPI validates request bodies against it and documents it in the OpenAPI page automatically: async def create(user: User). As a response_model, it filters what you return to exactly the declared fields.

A worked example

The sample user produces four classes in the order Address, Item, Order, User, so each is defined before it is used. The order’s coupon, present in only one order, becomes coupon: str | None = None and sits after order_id, total and items.

Tightening the models

Add constraints the sample cannot show: EmailStr for emails, Field(gt=0) for positive totals, Literal["active", "closed"] for status values. Then keep one real payload in a test so a changed API fails loudly in CI rather than quietly in production.

Lists at the root

When the JSON is a list of records, the generated class describes one record. In Pydantic v2, validate the whole list with a TypeAdapter(list[User]), which gives the same error reporting as a model; with dataclasses, build each item in a list comprehension.

Generate the frontend types with JSON to TypeScript, turn an API example into Python code with cURL to Fetch, inspect payloads in the JSON Formatter, or move settings files around with the TOML Converter.

Checked against the current version of the JSON to Pydantic & dataclass on .

Troubleshooting

The file does not open

Check that it is one of the supported formats above and opens in another app. Damaged files and password-protected PDFs cannot be read until they are repaired or unlocked.

It is slow or stops on a very large file

Everything runs on your device, so speed depends on its memory. Close other tabs, use a computer rather than a phone, or split the file into smaller parts first.

The download did not start

Look for your browser’s download bar or icon. Some browsers ask once before a site may download files; allow it and click the button again.

Frequently asked questions

Should I choose Pydantic or dataclasses?

Pydantic validates and converts data as it is loaded, which is what you want for input from outside your program. Dataclasses are lighter and part of the standard library, fine for data you already trust.

How do I serialise back to the original keys?

Call model.model_dump(by_alias=True) or model.model_dump_json(by_alias=True). Without by_alias, Pydantic writes the Python attribute names.

Why is id renamed to id_?

id, type, list and similar names are Python builtins. Shadowing them inside a class works but confuses linters and readers, so the attribute gets an underscore and an alias keeps the JSON key id.

Does it work with Pydantic v1?

The output targets Pydantic v2 (model_config, ConfigDict). For v1, replace model_config with an inner class Config: allow_population_by_field_name = True; the field definitions are the same.

Why is there “from __future__ import annotations”?

It lets the type hints use the modern X | None syntax on Python 3.8 and 3.9 and refer to classes in any order.

Keep working with the result

openWorkstand also includes a free workspace with documents, spreadsheets, tasks, projects and a calendar that save to a folder on your computer.