DEV Community

Avinash Verma
Avinash Verma

Posted on • Originally published at jsonviewertool.com

JSON to Python: dataclass, TypedDict, or Pydantic?

You've got JSON and you want typed Python objects instead of raw dicts. There are three good targets — dataclass, TypedDict, and Pydantic — and they solve different problems. Here's how to choose.

The shape

{ "id": 1, "name": "Ada", "active": true }
Enter fullscreen mode Exit fullscreen mode

dataclass — plain typed objects

from dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
    active: bool
Enter fullscreen mode Exit fullscreen mode

Attribute access (user.name), no validation — you still parse the JSON yourself: User(**json.loads(s)). Good for internal data you trust.

TypedDict — a dict with a known shape

from typing import TypedDict

class User(TypedDict):
    id: int
    name: str
    active: bool
Enter fullscreen mode Exit fullscreen mode

Still a plain dict at runtime (user["name"]) — the types are for the type-checker only, no runtime validation. Great for typing data you keep as dicts.

Pydantic — validation at the boundary

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    active: bool

user = User.model_validate_json(s)  # raises on bad data
Enter fullscreen mode Exit fullscreen mode

Parses and validates — wrong types raise instead of corrupting silently. The right choice for untrusted input (API bodies, config, webhooks).

jsonviewertool.com/json-to-python generates the class for whichever style you pick, from a JSON sample.

How to choose

  • Trusted internal data, want objectsdataclass.
  • Keep it as dicts, just want type hintsTypedDict.
  • Data crossing a trust boundaryPydantic (validate once, trust after).

The same caveat applies everywhere: a generator infers types from one example, so it can't see nullability, optional fields, or unions. Read the output before you ship it.

Top comments (0)