Dataclass Utilities

Dataclass-to-JSON-schema conversion utilities for form generation

Schema Metadata Constants

Constants for field metadata keys used in dataclass-to-JSON-schema conversion. Use these in dataclass field metadata dicts to control JSON schema generation.

Type Conversion

# Test type conversion
from typing import List, Optional

assert _python_type_to_json_type(str) == {"type": "string"}
assert _python_type_to_json_type(int) == {"type": "integer"}
assert _python_type_to_json_type(float) == {"type": "number"}
assert _python_type_to_json_type(bool) == {"type": "boolean"}
assert _python_type_to_json_type(List[str]) == {"type": "array", "items": {"type": "string"}}
print("Type conversion tests passed")
Type conversion tests passed

Dataclass to JSON Schema Conversion


source

dataclass_to_jsonschema

 dataclass_to_jsonschema (cls:type)

Convert a dataclass to a JSON schema for form generation.

Type Details
cls type Dataclass with field metadata
Returns Dict JSON schema dictionary
# Test dataclass_to_jsonschema
from dataclasses import dataclass, field
from typing import ClassVar

@dataclass
class TestConfig:
    __schema_name__: ClassVar[str] = "test_config"
    __schema_title__: ClassVar[str] = "Test Configuration"
    __schema_description__: ClassVar[str] = "A test configuration"
    
    name: str = field(
        default="default",
        metadata={SCHEMA_TITLE: "Name", SCHEMA_DESC: "The name"}
    )
    count: int = field(
        default=10,
        metadata={SCHEMA_TITLE: "Count", SCHEMA_MIN: 1, SCHEMA_MAX: 100}
    )
    tags: list = field(
        default_factory=list,
        metadata={SCHEMA_TITLE: "Tags"}
    )

schema = dataclass_to_jsonschema(TestConfig)
assert schema["name"] == "test_config"
assert schema["title"] == "Test Configuration"
assert schema["properties"]["name"]["title"] == "Name"
assert schema["properties"]["count"]["minimum"] == 1
assert schema["properties"]["count"]["maximum"] == 100
assert schema["properties"]["tags"]["default"] == []
print("dataclass_to_jsonschema tests passed")
dataclass_to_jsonschema tests passed