Convert JSON String Values to Python Enums

Learn how to convert JSON fields with a fixed set of string values into Python Enum classes. Covers StrEnum, auto(), and integration with dataclasses and Pydantic.

Advanced Patterns

Detailed Explanation

JSON Categorical Values as Python Enums

When a JSON field only takes a fixed set of values (like status, role, or priority), converting it to a Python Enum provides type safety and prevents invalid values.

Example JSON

{
  "id": 1,
  "status": "active",
  "role": "admin",
  "priority": "high"
}

Generated Python

from dataclasses import dataclass
from enum import StrEnum

class Status(StrEnum):
    ACTIVE = "active"
    INACTIVE = "inactive"
    PENDING = "pending"

class Role(StrEnum):
    ADMIN = "admin"
    EDITOR = "editor"
    VIEWER = "viewer"

class Priority(StrEnum):
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"

@dataclass
class Ticket:
    id: int
    status: Status
    role: Role
    priority: Priority

Why StrEnum?

StrEnum (Python 3.11+) makes enum members also be strings:

Status.ACTIVE == "active"  # True
str(Status.ACTIVE)  # "active"
json.dumps({"status": Status.ACTIVE})  # '{"status": "active"}'

This means JSON serialization works without custom encoders.

For Python < 3.11

from enum import Enum

class Status(str, Enum):
    ACTIVE = "active"
    INACTIVE = "inactive"
    PENDING = "pending"

Inheriting from both str and Enum achieves the same behavior.

With Pydantic

Pydantic validates enum values automatically:

from pydantic import BaseModel

class Ticket(BaseModel):
    id: int
    status: Status

# Valid
Ticket(id=1, status="active")  # Pydantic coerces string to enum

# Invalid — raises ValidationError
Ticket(id=1, status="unknown")

Integer Enums

For numeric categorical values:

from enum import IntEnum

class Priority(IntEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

When to Use Enums

  • Fixed set of values — statuses, roles, priorities, categories.
  • Type safety — prevents assigning arbitrary strings.
  • Autocompletion — IDE suggests valid values.
  • Exhaustive matchingmatch statement warns about unhandled cases (Python 3.10+).

Use Case

You are building a ticket management system where status, role, and priority must be constrained to specific values, and you want mypy to catch invalid assignments at development time.

Try It — JSON to Python Converter

Open full tool