Skip to content

JSON to Python dataclass converter

Paste a JSON sample. Python dataclasses are written beside it.

Dataclasses do not parse JSON on their own. Nested dictionaries stay dictionaries unless you convert them, for example with dacite or a from_dict method.

Ctrl+Enter or ⌘+Enter runs this tool immediately.

JSON sample
Python

Waiting for input.

Parsing stays in this browser. Input is not uploaded or saved.

How to use this tool

  1. Paste a JSON response or file, or load the sample.
  2. Read the dataclasses. Nested objects are defined first, so each class can refer to the ones above it.
  3. Copy the module, then load data with a library such as dacite, or write a from_dict method for nested fields.

Supported formats and limitations

  • The output uses list[str] and X | None, which need Python 3.10 or newer at runtime. The __future__ import lets annotations work on 3.7 and newer.
  • Keys that are not valid Python names, such as elevation-m or class, become elevation_m and class_. Map them back when you load the JSON.
  • Optional fields are moved to the end of each class with a default of None, because dataclass fields without defaults must come first.
  • A whole number in one item and a decimal in another become float. A field that is only null becomes None.

Examples

An optional field

alert appears in one forecast item, so it becomes alert: str | None = None at the end of the class.

{"forecast": [{"day": "Mon"}, {"day": "Tue", "alert": "wind"}]}

A renamed key

elevation-m is not a valid name, so the field is elevation_m. A notice reminds you to map it back.

{"elevation-m": 114}

Common errors and solutions

Expected double-quoted property name
The sample is not strict JSON. Remove trailing commas and comments, or paste the raw response body.

FAQ

Can I get Pydantic models instead?
The output is standard library dataclasses. Change @dataclass to a class that extends BaseModel and the field annotations work in Pydantic as written.
Why are some fields at the end of the class?
Fields with a default of None must come after fields without one, or Python raises a TypeError when the class is defined.
Is the JSON uploaded?
No. Classes are generated in your browser.

Related tools

  • JSON to TypeScript converter

    Generate TypeScript interfaces from a JSON sample in the browser. Array items are merged, and keys missing from some items become optional.

  • JSON Schema generator

    Generate a draft 2020-12 JSON Schema from a JSON sample in the browser. Types, nested objects, array items, and required keys are inferred.

  • JSON validator

    Check JSON syntax in the browser. Errors give a line and column, and duplicate keys that JSON.parse would silently drop are reported.