dataclasses-jsonschema

2.16.0 · active · verified Fri Apr 17

The `dataclasses-jsonschema` library (current version 2.16.0) provides a straightforward way to generate JSON schemas from Python dataclasses. It augments dataclasses with a `JsonSchemaMixin` to expose schema generation capabilities and includes utilities for type conversion. The library maintains an active release cadence, frequently addressing bug fixes, improving type handling, and adding support for newer Python features.

Common errors

Warnings

Install

Imports

Quickstart

Define a dataclass that inherits from `JsonSchemaMixin`. Then, call the static method `.json_schema()` on the dataclass to retrieve the generated JSON schema. This example demonstrates basic field types and metadata usage.

from dataclasses import dataclass, field
from datetime import datetime
from dataclasses_jsonschema import JsonSchemaMixin

@dataclass
class Person(JsonSchemaMixin):
    name: str
    age: int = field(metadata=dict(description="Age in years"))
    birth_date: datetime
    # Example with an optional field
    email: str | None = None # Use typing.Optional for Python < 3.10

# Generate the JSON schema
schema = Person.json_schema()

# Print the generated schema
import json
print(json.dumps(schema, indent=2))

view raw JSON →