Handle Optional and Nullable JSON Fields in Python

Learn how to convert JSON fields that may be null or absent into Python Optional types. Covers Optional[T], T | None syntax, and default values.

Type Annotations

Detailed Explanation

Optional Fields in Python

JSON fields can be null or entirely absent. Python represents these with Optional[T] (from the typing module) or the newer T | None syntax (Python 3.10+).

Example JSON

{
  "id": 1,
  "name": "Alice",
  "bio": null,
  "avatar_url": null,
  "phone": "555-1234"
}

Generated Python

from dataclasses import dataclass
from typing import Optional

@dataclass
class User:
    id: int
    name: str
    bio: Optional[str]
    avatar_url: Optional[str]
    phone: Optional[str]

Optional vs Required

  • Required field — Always present, never null. Type: str, int, etc.
  • Nullable field — Present but may be null. Type: Optional[str] (which means str | None).
  • Optional field — May be absent entirely. Type: Optional[str] with a default of None.

Python 3.10+ Syntax

@dataclass
class User:
    id: int
    name: str
    bio: str | None = None
    avatar_url: str | None = None
    phone: str | None = None

The X | None syntax is more concise and now the preferred style in modern Python.

Handling None at Runtime

if user.bio is not None:
    print(user.bio.upper())  # safe — mypy knows bio is str here
else:
    print("No bio provided")

Type checkers like mypy narrow the type inside the if branch, preventing AttributeError on None.

Multiple JSON Samples

When the converter sees multiple JSON samples where a field is sometimes present and sometimes missing, it marks that field as Optional with a default:

@dataclass
class User:
    id: int
    name: str
    bio: Optional[str] = None  # missing in some samples

Best Practices

  1. Use Optional only when None is a valid value — do not make everything optional "just in case."
  2. Provide a default of None when the field may be absent from the JSON payload.
  3. Use strict mypy settings (--strict) to catch unhandled None values.

Use Case

Your API returns user profiles where some fields like bio, avatar, and phone number may be null depending on what the user has filled in, and you need mypy to catch unhandled None access.

Try It — JSON to Python Converter

Open full tool