Skip to main content

Convert JSON Schema definitions to Pydantic models dynamically at runtime

Project description

jsonschema-pydantic-converter

CI PyPI Python Versions License

Convert JSON Schema definitions to Pydantic models dynamically at runtime.

Overview

jsonschema-pydantic-converter is a Python library that transforms JSON Schema dictionaries into Pydantic v2 models. This is useful when you need to work with dynamic schemas, validate data against JSON Schema specifications, or bridge JSON Schema-based systems with Pydantic-based applications.

Features

  • Dynamic Model Generation: Convert JSON Schema to Pydantic models at runtime
  • Comprehensive Type Support:
    • Primitive types (string, number, integer, boolean, null)
    • Arrays with typed items
    • Nested objects
    • Enums
    • Union types (anyOf)
    • Combined schemas (allOf)
  • Schema References: Support for $ref and $defs/definitions
  • Field Metadata: Preserves titles, descriptions, and default values
  • Self-References: Handle recursive schema definitions
  • Pydantic v2 Compatible: Built for Pydantic 2.0+

Installation

pip install jsonschema-pydantic-converter

Or using uv:

uv add jsonschema-pydantic-converter

Usage

Basic Example

from jsonschema_pydantic_converter import transform

# Define a JSON Schema
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string", "description": "User's name"},
        "age": {"type": "integer", "description": "User's age"},
        "email": {"type": "string"}
    },
    "required": ["name", "age"]
}

# Convert to Pydantic model
UserModel = transform(schema)

# Use the model
user = UserModel(name="John Doe", age=30, email="john@example.com")
print(user.model_dump())
# {'name': 'John Doe', 'age': 30, 'email': 'john@example.com'}

Working with Enums

schema = {
    "type": "object",
    "properties": {
        "status": {
            "type": "string",
            "enum": ["active", "inactive", "pending"]
        }
    }
}

StatusModel = transform(schema)
obj = StatusModel(status="active")

Nested Objects

schema = {
    "type": "object",
    "properties": {
        "user": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "email": {"type": "string"}
            },
            "required": ["name"]
        }
    }
}

Model = transform(schema)
data = Model(user={"name": "Alice", "email": "alice@example.com"})

Arrays

schema = {
    "type": "object",
    "properties": {
        "tags": {
            "type": "array",
            "items": {"type": "string"}
        }
    }
}

TagsModel = transform(schema)
obj = TagsModel(tags=["python", "pydantic", "json-schema"])

Schema with References

schema = {
    "type": "object",
    "properties": {
        "person": {"$ref": "#/$defs/Person"}
    },
    "$defs": {
        "Person": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"}
            }
        }
    }
}

Model = transform(schema)
person = Model(person={"name": "Bob", "age": 25})

Union Types (anyOf)

schema = {
    "type": "object",
    "properties": {
        "value": {
            "anyOf": [
                {"type": "string"},
                {"type": "integer"}
            ]
        }
    }
}

Model = transform(schema)
obj1 = Model(value="text")
obj2 = Model(value=42)

Development Setup

Prerequisites

  • Python 3.10 or higher
  • uv (recommended) or pip

Clone the Repository

git clone https://github.com/akshaylive/jsonschema-pydantic-converter.git
cd jsonschema-pydantic-converter

Install Dependencies

Using uv (recommended):

uv sync

Using pip:

pip install -e .
pip install mypy ruff pytest pytest-cov

Run Tests

# Using uv
uv run pytest

# With coverage
uv run pytest --cov=src --cov-report=html

# Using pytest directly (if in activated venv)
pytest

Code Quality

The project uses several tools to maintain code quality:

# Type checking with mypy
uv run mypy src/

# Linting with ruff
uv run ruff check .

# Format code with ruff
uv run ruff format .

Contributing

Contributions are welcome! Here's how you can help:

Reporting Issues

  • Check existing issues before creating a new one
  • Provide a clear description of the problem
  • Include a minimal reproducible example
  • Specify your Python and Pydantic versions

Submitting Pull Requests

  1. Fork the repository
  2. Create a new branch for your feature/fix:
    git checkout -b feature/your-feature-name
    
  3. Make your changes and ensure:
    • All tests pass: uv run pytest
    • Code is properly formatted: uv run ruff format .
    • No linting errors: uv run ruff check .
    • Type checking passes: uv run mypy src/
  4. Add tests for new functionality
  5. Update documentation if needed
  6. Commit your changes with clear commit messages
  7. Push to your fork and submit a pull request

Code Style

  • Follow PEP 8 guidelines
  • Use Google-style docstrings
  • Type hints are required for all functions
  • Line length: 88 characters (Black/Ruff default)

Development Guidelines

  • Write tests for all new features
  • Maintain backwards compatibility when possible
  • Update the README for user-facing changes
  • Keep dependencies minimal

Limitations

  • Optional fields without defaults are set to None rather than using Optional[T] type annotation to maintain JSON Schema round-trip consistency
  • Complex schema combinations may require testing for edge cases

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Maintainer

Akshaya Shanbhogue - akshay.live@gmail.com

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jsonschema_pydantic_converter-0.0.1.tar.gz (43.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jsonschema_pydantic_converter-0.0.1-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

Details for the file jsonschema_pydantic_converter-0.0.1.tar.gz.

File metadata

File hashes

Hashes for jsonschema_pydantic_converter-0.0.1.tar.gz
Algorithm Hash digest
SHA256 012fd756420656845519b8815590308c1f776814703c3bf6859981deaf8a5acb
MD5 c10ea846772e3c359d898dd70b930400
BLAKE2b-256 db2b016aceec88bb1d1d105fd219f131718247a51da663dd41e7ef597380580a

See more details on using hashes here.

Provenance

The following attestation bundles were made for jsonschema_pydantic_converter-0.0.1.tar.gz:

Publisher: publish.yml on akshaylive/jsonschema-pydantic-converter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file jsonschema_pydantic_converter-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for jsonschema_pydantic_converter-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 42792bbcc3dbe7fde50f5d5008755d6aa7a4fcb9946263daebeb6f99e4865faf
MD5 9a18cf916cacbf5e72c192572cae4224
BLAKE2b-256 00f3da34e61d6551d24f314245aeead45ffa21047d9115b5a8cd76b927468e80

See more details on using hashes here.

Provenance

The following attestation bundles were made for jsonschema_pydantic_converter-0.0.1-py3-none-any.whl:

Publisher: publish.yml on akshaylive/jsonschema-pydantic-converter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page