Python Dataclass Fields with Default Values from JSON

Learn how to set default values on dataclass fields when converting JSON to Python. Covers default factories for mutable types, field ordering rules, and Optional defaults.

Dataclasses

Detailed Explanation

Default Values in Dataclasses

When JSON fields may be absent or have sensible defaults, you can set default values on dataclass fields. Python enforces that fields with defaults come after fields without.

Example JSON

{
  "name": "Alice",
  "role": "viewer",
  "tags": [],
  "bio": null
}

Generated Python

from dataclasses import dataclass, field
from typing import Optional

@dataclass
class User:
    name: str
    role: str = "viewer"
    tags: list[str] = field(default_factory=list)
    bio: Optional[str] = None

Field Ordering Rule

Python requires that all fields without defaults come before fields with defaults:

# Valid
@dataclass
class User:
    name: str          # no default
    role: str = "viewer"  # has default

# Invalid — TypeError at class definition
@dataclass
class User:
    role: str = "viewer"
    name: str          # no default after defaulted field

The converter automatically reorders fields to satisfy this constraint.

Mutable Default Trap

Never use a mutable object as a default directly:

# WRONG — all instances share the same list
@dataclass
class User:
    tags: list[str] = []

# CORRECT — each instance gets a new list
@dataclass
class User:
    tags: list[str] = field(default_factory=list)

field(default_factory=list) calls list() for each new instance, preventing the classic mutable-default-argument bug.

Optional Fields with None

Fields that may be null in JSON use Optional[T] (or T | None in Python 3.10+) with a default of None:

bio: Optional[str] = None

Default Factory for Dicts

metadata: dict[str, str] = field(default_factory=dict)

When to Use Defaults

  • API responses where certain fields are optional
  • Configuration objects with sensible fallbacks
  • Builder patterns where fields are populated incrementally

Use Case

You are building a configuration loader that reads JSON files where most fields have sensible defaults, and you want your dataclass to work both with full JSON payloads and minimal ones.

Try It — JSON to Python Converter

Open full tool