go-supertools
Developer & Data Tools

JSON to Python Dataclass Converter

Generate Python dataclasses, Pydantic models or TypedDicts from sample JSON.

Runs in your browser Your input never leaves your device.

0 characters | 0 words

Report a problem with this tool

About this tool

Paste a sample of your JSON and choose the style of Python code you want. Dataclasses are plain classes with type hints; Pydantic models (version 2) also validate data and map JSON keys with aliases when a key is not a valid Python name; TypedDicts describe dictionaries that you already load with json.load, with NotRequired for optional keys. Field names are converted to snake_case, Python keywords get an underscore (class becomes class_), and the original key is kept in a comment or alias. Optional fields have the type | None and default to None. The shape is inferred from your sample: objects become named types, lists become list types, a key that is missing from some items of a list becomes optional, numbers without a fraction become integers (a list that mixes 1 and 2.5 is decimal), and a value that is sometimes one type and sometimes another becomes a union or a general type. The same shape in two places shares one type. Keys that are not valid names, such as 'user name', are converted and the original key is kept. To check the output we ran it with Python 3.12: Pydantic models validated each of 37 samples and refused a copy with one damaged value, dataclasses were filled from the sample by a small reader that follows the type hints, and TypedDicts were loaded and their hints resolved. Types use the syntax of Python 3.10 and later (list[str], X | None); the TypedDict style also needs Python 3.11 for NotRequired, or typing_extensions on older versions. Your JSON is processed in your browser and never uploaded. A JSON number such as 10.0 or 1e3 is read as a whole number, because the sample loses how it was written; tick Treat all numbers as decimals if your values can have a fraction.

How to use it

  1. Paste a sample of your JSON, a longer or more varied sample gives a better result.
  2. Set the name of the top-level type, and the options.
  3. Copy the code into your project.
  4. Adjust names and types that the sample could not tell, such as dates in strings.

Common problems

Pydantic does not accept my JSON key
Use the Pydantic style: it adds an alias for keys that are not valid Python names, and the model accepts the original key.
A dataclass does not parse my JSON by itself
Dataclasses do not read JSON. Use the Pydantic style, or a library such as dacite, to build them from a dictionary.
Field order is not the same as the JSON
Dataclass fields with defaults must come after those without, so optional fields move to the end.