JSON to Python Dataclass & Pydantic Model
Paste JSON and get typed Python classes for every nested object, as standard-library dataclasses or Pydantic BaseModel models. Free, no signup, and generated in your browser so nothing is uploaded.
16 lines · processed in your browser, nothing is uploaded
Python output · root.py
Generated code appears here.Example: JSON to Python
This JSON sample, with the root type named User, produces the Python below using the default options.
{
"id": 1024,
"name": "Ada Lovelace",
"email": "ada@example.com",
"active": true,
"score": 98.5,
"tags": [
"admin",
"beta"
],
"address": {
"city": "London",
"postcode": "NW1 6XE"
}
}from dataclasses import dataclass
from typing import List
@dataclass
class Address:
city: str
postcode: str
@dataclass
class User:
id: int
name: str
email: str
active: bool
score: float
tags: List[str]
address: Address
How to convert JSON to Python
- 1Paste a JSON object or array into the input.
- 2Select Python as the output language.
- 3Choose the model style: dataclasses or Pydantic BaseModel.
- 4Pick your target Python version: 3.6, 3.7+ or 3.10+.
- 5Name the root class, for example Product.
- 6Copy the code or download it as a .py file.
Dataclasses or Pydantic?
Standard-library dataclasses give you typed containers with no dependencies, but they do not validate or coerce values; a string where an int is expected passes silently. They suit internal data you already trust.
Pydantic models validate and convert data on construction and raise clear errors for bad input. They suit API responses, config files and request bodies, and frameworks such as FastAPI use them directly. Pick the style with the model style option.
Using the generated Pydantic models
Install pydantic, then parse a dict with Product.model_validate(data) in Pydantic v2 (parse_obj in v1), or a raw string with Product.model_validate_json(text). Invalid input raises a ValidationError that lists every failing field.
If a JSON key is not a valid Python identifier or you want a different attribute name, map it with Field(alias="original-key").
Python version and optional fields
The version setting controls which language features and typing syntax the output may use. Set it to the oldest Python version you deploy to; standard-library dataclasses, for example, only exist from Python 3.7.
A field that can be missing or null is typed as optional and should default to None. Paste several records so the generator can see which keys are sometimes absent or null.