Convert JSON to Python TypedDict for Dict-Like Access

Learn how to convert JSON to Python TypedDict for type-safe dictionary access without changing from dict syntax. Covers total, NotRequired, and ReadOnly.

Pydantic & TypedDict

Detailed Explanation

JSON to TypedDict

TypedDict (from typing) lets you add type annotations to dictionaries without changing the dict interface. Unlike dataclasses, TypedDict values are accessed with bracket notation (d["key"]).

Example JSON

{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com",
  "role": "admin"
}

Generated Python

from typing import TypedDict

class User(TypedDict):
    id: int
    name: str
    email: str
    role: str

Usage

import json

data: User = json.loads(raw_json)
print(data["name"])  # "Alice" — type checker knows this is str

TypedDict vs Dataclass

Feature TypedDict dataclass
Access syntax d["key"] d.key
Runtime type dict Custom class
json.loads() compatible Yes (directly) No (need construction)
Instance methods No Yes
Validation None None (or Pydantic)

Optional Keys with NotRequired

from typing import TypedDict, NotRequired

class User(TypedDict):
    id: int
    name: str
    bio: NotRequired[str]  # may be absent

Total vs Partial

By default, all keys are required (total=True). Set total=False to make all keys optional:

class PartialUser(TypedDict, total=False):
    id: int
    name: str
    email: str

ReadOnly (Python 3.13+)

from typing import ReadOnly

class Config(TypedDict):
    version: ReadOnly[str]
    debug: bool

When to Choose TypedDict

  • You want dict-style access (data["key"]) instead of attribute access.
  • You are working with existing dict-based code and want to add type safety without refactoring.
  • Your data comes directly from json.loads() and you want zero-overhead type checking.
  • You are annotating third-party APIs that return plain dicts.

Nested TypedDicts

class Address(TypedDict):
    street: str
    city: str

class User(TypedDict):
    name: str
    address: Address

The nested value is still a plain dict at runtime, but the type checker enforces the shape.

Use Case

You are adding type safety to an existing codebase that passes JSON-parsed dicts everywhere, and you want mypy coverage without refactoring every function to accept dataclass instances.

Try It — JSON to Python Converter

Open full tool