Dataclass vs TypedDict vs Pydantic: Typing JSON Data in Python

Compare three ways to model JSON in Python: TypedDict, dataclasses and Pydantic. See how each handles validation, nested data, optional keys and camelCase.

Updated September 29, 2026 6 min read

Use the free JSON to Python ClassCreate Python dataclasses, TypedDicts or Pydantic models from JSON

In Python, json.loads hands you nested dictionaries and lists. That is quick to start with, but as a codebase grows, order["totl"] typos, missing keys and "is this a string or a number?" questions start to cost time. Adding types to that data lets your editor autocomplete field names and lets a type checker such as mypy or Pyright catch mistakes before they run.

Python offers three common ways to describe a JSON shape: TypedDict, @dataclass and Pydantic's BaseModel. They look similar in source code but behave very differently at runtime. This guide compares them on the questions that matter for JSON (validation, nested objects, optional keys and camelCase names) and shows how to generate any of the three from a sample.

The same JSON, three models

Take this fragment of an API response:

{ "orderId": "A-101", "total": 12, "items": 1, "coupon": "SPRING10" }

where coupon appears in some orders but not others.

TypedDict: types for plain dictionaries

import json
from typing import NotRequired, TypedDict   # NotRequired: Python 3.11+

class Order(TypedDict):
    orderId: str
    total: float
    items: int
    coupon: NotRequired[str]

order: Order = json.loads(raw)

A TypedDict is only a description for the type checker. At runtime the value is still an ordinary dict; nothing is converted or checked. The keys keep their JSON spelling, including camelCase, because they are the JSON keys. NotRequired marks keys that may be absent.

dataclass: real objects, no validation

from dataclasses import dataclass
from typing import Optional

@dataclass
class Order:
    order_id: str
    total: float
    items: int
    coupon: Optional[str] = None

A dataclass gives you real objects with attribute access (order.total), a readable repr and equality. But it does not parse anything: Order(**data) fails when JSON keys (orderId) don't match field names (order_id), and passing "12" for total is accepted without complaint. Nested dataclasses are not built automatically either; profile stays a plain dict unless you convert it yourself.

Pydantic: parsing and validation

from typing import Optional
from pydantic import BaseModel, Field

class Order(BaseModel):
    order_id: str = Field(alias="orderId")
    total: float
    items: int
    coupon: Optional[str] = None

order = Order.model_validate(data)          # Pydantic v2
payload = order.model_dump(by_alias=True)   # back to camelCase keys

Pydantic reads the JSON keys through aliases, builds nested models, converts compatible values (the string "12" becomes 12.0 in lax mode) and raises a ValidationError listing every field that is wrong. It is a third-party package (pip install pydantic) and does more work per object than the other two.

Side-by-side comparison

TypedDict dataclass Pydantic BaseModel
Runtime object plain dict class instance class instance
Validates types at runtime No No Yes
Builds nested objects n/a (dicts) No, manual Yes
camelCase JSON keys Kept as-is Must be mapped by hand alias= per field
Extra dependency No No Yes
Best for Typing existing dict code Internal data you trust Data from outside your program

A practical rule: validate at the boundary, where JSON enters your program from a request, file or third-party API, and that is where Pydantic earns its keep. Inside the program, where data is already known to be good, dataclasses are lightweight and dependency-free. TypedDict is ideal when you want type-checking on code that already passes dictionaries around, without changing any runtime behaviour.

Generate the classes from a JSON sample

Writing classes for a large response by hand is tedious. JSON to Python Class generates all three styles from a sample.

  1. Open JSON to Python Class and paste a response into JSON sample, click Open file, or use Load sample.
  2. Enter a Root type name, such as User or Invoice.
  3. Choose Output style: @dataclass, TypedDict or Pydantic BaseModel.
  4. For dataclasses, keep snake_case field names on to get Pythonic names; each renamed field gets a # JSON key: "..." comment so you can see the original.
  5. Review the Python classes output, then Copy it or Download a .py file.

A few details of the output are worth knowing:

  • Nested objects become their own classes, and objects with identical shapes share one class.
  • Keys missing from some items in an array become optional: Optional[...] = None in dataclasses and Pydantic, and NotRequired[...] in TypedDict.
  • Dataclass fields with defaults are placed after the required ones, because Python requires that order.
  • Pydantic models always use snake_case names with Field(alias="originalKey"), so they parse the original JSON directly.
  • TypedDict keeps the original keys. If a key is not a valid Python identifier (for example it contains a hyphen), the functional TypedDict("Name", {...}) syntax is used instead.
  • Timestamps are typed as str, and a key that is only null in the sample becomes Any. Tighten those types by hand, for example to datetime, which Pydantic parses from ISO 8601 strings.

Loading JSON into generated dataclasses

Because dataclasses don't parse, you need a small loader when names or nesting differ. For one level:

import json

raw = json.loads(text)
order = Order(
    order_id=raw["orderId"],
    total=raw["total"],
    items=raw["items"],
    coupon=raw.get("coupon"),
)

For deeply nested data this becomes repetitive, which is the point at which Pydantic, or a dedicated converter library, pays off.

Tips and pitfalls

One sample is not a contract

The generator only knows what the sample shows. If total is 12 in every example you pasted, it may be typed int when the API can also send 12.5. Paste an array with several varied records, or check the API documentation. If you need a formal contract, create one with the JSON Schema Generator; see how to create a JSON Schema from sample data.

Python version

Generated code starts with from __future__ import annotations and uses typing.List and Optional, which works on older Python 3 versions too. NotRequired needs Python 3.11, or typing_extensions on earlier versions.

Pydantic v1 versus v2

The generated models work in both, but method names differ: v2 uses model_validate and model_dump, while v1 used parse_obj and dict().

Invalid input

If the sample does not parse, clean it up with the JSON Formatter first. Working in more than one language? The same sample can produce Go structs or a Zod schema for TypeScript.

Frequently asked questions

Should I use a dataclass or Pydantic for API responses?

Use Pydantic when the data comes from outside your program and you want it validated and converted. Dataclasses suit internal data that is already trusted.

Does a TypedDict check types at runtime?

No. A TypedDict is only used by type checkers and editors; at runtime the value is a normal dictionary.

How do I map camelCase JSON keys to snake_case in Python?

With Pydantic, give each field an alias such as Field(alias="orderId"). With dataclasses, map the keys yourself when constructing the object.

Can dataclasses create nested objects from JSON automatically?

No. Order(**data) leaves nested values as dictionaries. Build nested dataclasses yourself or use Pydantic, which does it automatically.

Is the JSON I paste sent anywhere?

No. The JSON to Python Class generator runs in your browser, so API responses and sample data stay on your device.

Try it now: JSON to Python Class

Loading tool…