Python reads JSON in one line. But what you get back is a lot of dictionaries and lists. Then you type data["user"]["address"]["city"] and hope every key is spelled right. If one is wrong, you only find out when the code runs.
Classes fix this. A class gives your data named fields, so your editor can help you. Some class types can even check the data for you. This guide shows the three common choices and when to use each one.
Quick answer: Read the JSON with json.loads(). Then load it into a dataclass, a Pydantic model or a TypedDict. Use Pydantic if you want the data checked and nested objects converted for you. Use TypedDict if you only want type hints.
What does json.loads give you?
json.loads() turns JSON text into plain Python values. (Use json.load(), without the “s”, to read from a file.) Each JSON type becomes a built-in Python type:
- An object becomes a
dict. - An array becomes a
list. - A string becomes a
str. - A whole number becomes an
int, and a decimal becomes afloat. trueandfalsebecomeTrueandFalse, andnullbecomesNone.
This works, but a dict has no fixed shape. Your editor can’t suggest keys, and a typo only shows up as a KeyError when the code runs.
Here is the sample we will use:
{
"id": 42,
"name": "Ada Lovelace",
"email": null,
"address": { "city": "London", "country": "UK" }
}Option 1: How to use dataclasses
A dataclass is a normal Python class that writes its own __init__ (setup method) for you. It is part of the standard library, so there is nothing to install.
import json
from dataclasses import dataclass
@dataclass
class Address:
city: str
country: str
@dataclass
class User:
id: int
name: str
email: str | None
address: Address
data = json.loads(text)
user = User(**{**data, "address": Address(**data["address"])})
print(user.address.city)Two things to know:
- Nested objects are not converted for you.
User(**data)would leaveaddressas a plain dict. You have to build the inner class yourself, as above. - Types are not checked. If
idarrives as the text"42", the dataclass just stores the text. The type hints are only for you and your editor.
The str | None syntax needs Python 3.10 or newer. On older versions, use Optional[str].
Option 2: How to use Pydantic models
Pydantic is a popular library that checks data against your class. It is used by FastAPI and many other projects. You install it with pip install pydantic.
from pydantic import BaseModel
class Address(BaseModel):
city: str
country: str
class User(BaseModel):
id: int
name: str
email: str | None = None
address: Address
user = User.model_validate_json(text)
print(user.address.city)Pydantic does the work that dataclasses leave to you:
- It reads the JSON text and builds the nested
Addressfor you. - It checks every field. A required field may be missing, or a value may have the wrong type. Then you get a clear
ValidationErrorthat names the field. - By default it converts close matches. The text
"42"becomes the number42. You can turn on strict mode if you don’t want that.
These examples use Pydantic version 2. If you already have a dict, use User.model_validate(data) instead.
Option 3: How to use TypedDict
A TypedDict describes the keys of a dict. It adds type hints only. At runtime your data is still a plain dict, and nothing is checked.
import json
from typing import TypedDict
class Address(TypedDict):
city: str
country: str
class User(TypedDict):
id: int
name: str
email: str | None
address: Address
user: User = json.loads(text)
print(user["address"]["city"])A type checker, such as mypy or Pyright, now warns you about wrong keys. This is useful when you want to keep working with dicts. For example, you may want to pass them straight back to json.dumps(). For keys that may be missing, wrap the type in NotRequired[…] (Python 3.11 or newer).
Which one should you pick?
- Pydantic when the data comes from outside your program: an API, a file, user input. You want it checked.
- Dataclasses when you trust the data and don’t want an extra library.
- TypedDict when you want type hints but need to keep plain dicts.
What about keys that aren’t valid Python names?
JSON keys can be any text. Python names can’t. A key like "user-name" has a dash, and "class" is a reserved word (a word Python keeps for itself). You can’t use either as a field name.
In Pydantic, give the field a valid Python name and tell it the real JSON key with an alias:
from pydantic import BaseModel, Field
class User(BaseModel):
user_name: str = Field(alias="user-name")
class_: str = Field(alias="class")
user = User.model_validate_json('{"user-name": "ada", "class": "admin"}')
print(user.user_name) # ada
print(user.model_dump(by_alias=True)) # original keys againWith TypedDict you can use the other way of writing it, which accepts any key: User = TypedDict("User", {"user-name": str}). With dataclasses, you have to rename the keys by hand before you create the object.
How to generate Python classes from JSON
Writing classes for a large API response takes a while. The JSON to Python generator does it for you:
- Paste a sample that is typical of your data.
- Set the name of the root class and pick dataclasses, Pydantic models or TypedDict.
- Copy the code or download it as a file.
Nested classes, arrays and optional fields are worked out from the sample. Some keys aren’t valid Python names, like user-name or class. They become snake_case fields (lowercase words joined by underscores) with an alias. So the Pydantic model still accepts the original JSON.
Nested classes are written before the classes that use them, so the file runs as it is.
If your sample is one long line, run it through the JSON Formatter first. It is much easier to check the generated classes against JSON you can actually read.
Remember that a generator only knows your sample. A field may be null in every item, or missing from all of them. In that case, check the result and fix the type yourself.
Do other teams or other languages need the same rules? Make a JSON Schema from the same sample with the JSON Schema Generator. A schema is a file that describes what valid data looks like. It works with any programming language. See what JSON Schema is.
Common questions
How do I convert JSON to a Python object?
Use json.loads() to get a dict, then pass it to a class. With Pydantic you can skip the first step: User.model_validate_json(text) reads the JSON text directly.
How do I turn a class back into JSON?
For a dataclass, use json.dumps(dataclasses.asdict(user)). For a Pydantic model, use user.model_dump_json(), and add by_alias=True to get the original key names back.
Is Pydantic better than dataclasses?
Not better, just different. Pydantic checks and converts data. You want that where data comes into your program. Dataclasses are lighter and built in, which is fine for data you already trust.
Why does json.loads fail on my data?
Often the text is a printed Python dict, with single quotes and True or None. That is not JSON. See the most common JSON errors for the fix.