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.2.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.2-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for jsonschema_pydantic_converter-0.0.2.tar.gz
Algorithm Hash digest
SHA256 bf848752ff1b84179e3f8fd2dd82a17b5dd31874356e73119a2f375f0520b529
MD5 56ee47bb801700de7ae81ee5feb5fe2f
BLAKE2b-256 7915ad571664781e8b1ce5407c3355ca141d8b60eceb68e2e54d5788e705a36c

See more details on using hashes here.

Provenance

The following attestation bundles were made for jsonschema_pydantic_converter-0.0.2.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.2-py3-none-any.whl.

File metadata

File hashes

Hashes for jsonschema_pydantic_converter-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 3699afe6c2f11007a71645a2434d5ca21e9ff05439d4881fa9010c9d99a8abbb
MD5 598208ee6b104ef49e34b4c9b263bfb4
BLAKE2b-256 f97bf6422ac6f57e61c9b46322d7f72a211d8b880d12c0ccd71a8c61ab017bc1

See more details on using hashes here.

Provenance

The following attestation bundles were made for jsonschema_pydantic_converter-0.0.2-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