JSON Schema Converter - PyCharter
Description: Data Contract Management, ETL Pipelines, and Quality Assurance for Python

Skip to content

# JSON Schema Converter

Convert Pydantic models to JSON Schema.

## Overview

    from pycharter import to_dict, to_file, to_json
    from pydantic import BaseModel

    class User(BaseModel):
        name: str
        age: int

    schema = to_dict(User)

## API Reference

### Output Functions

## `` to_dict

    to_dict(
        model: Type[BaseModel],
        title: str | None = None,
        description: str | None = None,
        version: str | None = None,
    ) -> dict[str, Any]

Convert a Pydantic model to a JSON Schema dictionary.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `Type[BaseModel]` | The Pydantic model class to convert | required
`title` | `str | None` | Optional title for the schema | `None`
`description` | `str | None` | Optional description for the schema | `None`
`version` | `str | None` | Optional version string (if not provided, extracted from model) | `None`

Returns:

Type | Description
--- | ---
`dict[str, Any]` | JSON Schema as a dictionary with version included if available

Example

> > > from pydantic import BaseModel, Field class Person(BaseModel): ... version = "1.0.0" ... name: str = Field(..., min_length=3) ... age: int = Field(ge=0) schema = to_dict(Person) schema["version"] "1.0.0" schema.get("properties", {}).get("name", {}).get("minLength") 3

Source code in `src/pycharter/json_schema_converter/reverse_converter.py`

    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    def to_dict(
        model: Type[BaseModel],
        title: str | None = None,
        description: str | None = None,
        version: str | None = None,
    ) -> dict[str, Any]:
        """
        Convert a Pydantic model to a JSON Schema dictionary.

        Args:
            model: The Pydantic model class to convert
            title: Optional title for the schema
            description: Optional description for the schema
            version: Optional version string (if not provided, extracted from model)

        Returns:
            JSON Schema as a dictionary with version included if available

        Example:
            >>> from pydantic import BaseModel, Field
            >>> class Person(BaseModel):
            ...     __version__ = "1.0.0"
            ...     name: str = Field(..., min_length=3)
            ...     age: int = Field(ge=0)
            >>> schema = to_dict(Person)
            >>> schema["version"]
            "1.0.0"
            >>> schema.get("properties", {}).get("name", {}).get("minLength")
            3
        """
        return model_to_schema(model, title=title, description=description, version=version)

## `` to_file

    to_file(
        model: Type[BaseModel],
        file_path: str,
        title: str | None = None,
        description: str | None = None,
        version: str | None = None,
        indent: int = 2,
    ) -> None

Convert a Pydantic model to a JSON Schema file.

Supports both JSON (.json) and YAML (.yaml, .yml) output formats. Format is automatically determined by file extension.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `Type[BaseModel]` | The Pydantic model class to convert | required
`file_path` | `str` | Path to the output file (JSON or YAML) | required
`title` | `str | None` | Optional title for the schema | `None`
`description` | `str | None` | Optional description for the schema | `None`
`version` | `str | None` | Optional version string (if not provided, extracted from model) | `None`
`indent` | `int` | JSON indentation level (ignored for YAML) | `2`

Example

> > > from pydantic import BaseModel class Product(BaseModel): ... version = "1.0.0" ... name: str ... price: float to_file(Product, "product_schema.json") # JSON output to_file(Product, "product_schema.yaml") # YAML output

Source code in `src/pycharter/json_schema_converter/reverse_converter.py`

     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    def to_file(
        model: Type[BaseModel],
        file_path: str,
        title: str | None = None,
        description: str | None = None,
        version: str | None = None,
        indent: int = 2,
    ) -> None:
        """
        Convert a Pydantic model to a JSON Schema file.

        Supports both JSON (.json) and YAML (.yaml, .yml) output formats.
        Format is automatically determined by file extension.

        Args:
            model: The Pydantic model class to convert
            file_path: Path to the output file (JSON or YAML)
            title: Optional title for the schema
            description: Optional description for the schema
            version: Optional version string (if not provided, extracted from model)
            indent: JSON indentation level (ignored for YAML)

        Example:
            >>> from pydantic import BaseModel
            >>> class Product(BaseModel):
            ...     __version__ = "1.0.0"
            ...     name: str
            ...     price: float
            >>> to_file(Product, "product_schema.json")  # JSON output
            >>> to_file(Product, "product_schema.yaml")  # YAML output
        """
        schema = model_to_schema(
            model, title=title, description=description, version=version
        )
        path = Path(file_path)
        path.parent.mkdir(parents=True, exist_ok=True)

        # Determine output format
        suffix = path.suffix.lower()

        if suffix in [".yaml", ".yml"]:
            with open(path, "w", encoding="utf-8") as f:
                yaml.dump(
                    schema, f, default_flow_style=False, sort_keys=False, allow_unicode=True
                )
        elif suffix == ".json":
            with open(path, "w", encoding="utf-8") as f:
                json.dump(schema, f, indent=indent)
        else:
            raise ValueError(
                f"Unsupported file format: {suffix}. Supported formats: .json, .yaml, .yml"
            )

## `` to_json

    to_json(
        model: Type[BaseModel],
        title: str | None = None,
        description: str | None = None,
        version: str | None = None,
        indent: int = 2,
    ) -> str

Convert a Pydantic model to a JSON Schema string.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `Type[BaseModel]` | The Pydantic model class to convert | required
`title` | `str | None` | Optional title for the schema | `None`
`description` | `str | None` | Optional description for the schema | `None`
`version` | `str | None` | Optional version string (if not provided, extracted from model) | `None`
`indent` | `int` | JSON indentation level | `2`

Returns:

Type | Description
--- | ---
`str` | JSON Schema as a JSON string

Example

> > > from pydantic import BaseModel class User(BaseModel): ... version = "1.0.0" ... name: str schema_json = to_json(User) print(schema_json)

Source code in `src/pycharter/json_schema_converter/reverse_converter.py`

    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    def to_json(
        model: Type[BaseModel],
        title: str | None = None,
        description: str | None = None,
        version: str | None = None,
        indent: int = 2,
    ) -> str:
        """
        Convert a Pydantic model to a JSON Schema string.

        Args:
            model: The Pydantic model class to convert
            title: Optional title for the schema
            description: Optional description for the schema
            version: Optional version string (if not provided, extracted from model)
            indent: JSON indentation level

        Returns:
            JSON Schema as a JSON string

        Example:
            >>> from pydantic import BaseModel
            >>> class User(BaseModel):
            ...     __version__ = "1.0.0"
            ...     name: str
            >>> schema_json = to_json(User)
            >>> print(schema_json)
        """
        schema = model_to_schema(
            model, title=title, description=description, version=version
        )
        return json.dumps(schema, indent=indent)

## Examples

    from pycharter import to_dict, to_file, to_json
    from pydantic import BaseModel

    class Product(BaseModel):
        name: str
        price: float
        in_stock: bool = True

    # To dictionary
    schema = to_dict(Product)
    print(schema)

    # To JSON string
    json_str = to_json(Product)

    # To file
    to_file(Product, "schemas/product.json")

## Round-Trip

    from pycharter import from_dict, to_dict

    # Generate model from schema
    User = from_dict(original_schema, "User")

    # Convert back to schema
    exported_schema = to_dict(User)

    # Schemas should be equivalent

## See Also

- Pydantic Generator