Advertisement

JSON to Python Dataclass / Pydantic Model

Paste JSON and get typed Python dataclasses or Pydantic v2 models: nested classes, list[...] and optional fields, snake_case names and a from_dict helper.

Builds nested objects and maps renamed keys back to the JSON names.

Generate typed Python classes from a JSON sample: nested objects, lists, nullable fields and original-key aliases. Choose standard-library dataclasses with an optional from_dict() helper, or Pydantic v2 models for runtime validation.

How to use this tool

  1. Paste a JSON object, or a list of objects — several samples let the tool spot optional fields.
  2. Type the name of the root class.
  3. Choose dataclass or Pydantic, and whether keys become snake_case.
  4. Copy the code into your project (Python 3.10 or newer).

Formula

string → str · whole number → int · decimal → float (int and float mixed → float) · true/false → bool · object → new class · array → list[item type] · null → | None · mixed types → Any

Missing keys become optional with a default of None; dataclasses place defaulted fields last. Nested class names come from keys, with list names singularized. Classes share a definition only when their derived name and fields match. Integer samples must stay within ±9,007,199,254,740,991. JavaScript numeric inference refuses nonfinite values or lost fractional parts; use strings for large identifiers or exact decimals.

Example

The default sample produces 3 classes and 16 fields: Address, Order and User. "total": 59.9 and "total": 12 merge into total: float; couponCode appears in only one order, so it becomes coupon_code: str | None = None; and "lastLogin": null becomes last_login: Any = None, because null alone gives no type. In from_dict(), orders is built with [Order.from_dict(x) for x in d["orders"]]. Switch to Pydantic and every renamed key gets Field(alias="userName") instead.

Frequently asked questions

Dataclass or Pydantic?

Dataclasses are built in and fast but do no validation or type conversion. Pydantic checks types, converts compatible values such as "12" to 12, and parses nested objects straight from a JSON string with model_validate_json(). Pydantic suits API boundaries; dataclasses suit internal data.

Why is a field float when my sample shows 12?

If any value for that key has a fractional part, the field becomes float. JSON 12.0 is read as the whole number 12, so include a sample with a real decimal such as 12.5 if a field can be fractional.

What happens to keys like "first-name" or "class"?

They become valid names: first-name → first_name and class → class_. from_dict() still reads the original key, and in Pydantic the original key becomes the alias.

Can I paste a list at the top level?

Yes. The items of [ {…}, {…} ] are merged into one root class; the note under the result shows how to parse the whole list.

Sources

Last updated: 2026-10-30

Advertisement