A Python library for automatically generating Pydantic v2 models from JSON Schema definitions
Maintained. Last release 6 weeks ago, commits in 2 of the last 26 weeks. Weaker on commit activity.
pip install json-schema-to-pydanticJSON Schema to Pydantic
A Python library for automatically generating Pydantic v2 models from JSON Schema definitions.
Features
- Converts JSON Schema to Pydantic v2 models
- Supports complex schema features including:
- References ($ref) with circular reference detection
- Combiners (allOf, anyOf, oneOf) with discriminated unions where possible
- Type constraints and validations
- Array and object validations
- Enums and constants (as
Literaltypes) - Format validations (email, uri, uuid, date, time, date-time)
- Top-level arrays and scalar types (not just objects)
- Underscore-prefixed fields (common in OpenAPI specs)
- Reuse of existing Pydantic models and types for
$refs - Custom base model class for generated models
- Full type hinting support
- Clean, simple API
Installation
pip install json-schema-to-pydantic
Development Setup
- Clone the repository
- Install development dependencies:
# Using uv (recommended)
uv sync --extra dev
# Or using pip
pip install -e ".[dev]"
- Run tests and linters:
uv run pytest
uvx ruff check .
Quick Start
from json_schema_to_pydantic import create_model
# Define your JSON Schema
schema = {
"title": "User",
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name", "email"]
}
# Generate your Pydantic model
UserModel = create_model(schema)
# Use the model
user = UserModel(
name="John Doe",
email="john@example.com",
age=30
)
# Example with relaxed validation
RelaxedModel = create_model(
{
"type": "object",
"properties": {
"tags": {"type": "array"}, # Array without items schema
"metadata": {} # Field without type
}
},
allow_undefined_array_items=True, # Allows arrays without items schema
allow_undefined_type=True # Allows fields without type (defaults to Any)
)
relaxed_instance = RelaxedModel(
tags=[1, "two", True],
metadata={"custom": "data"}
)
# Example with underscore-prefixed fields (common in OpenAPI)
OpenAPIModel = create_model(
{
"type": "object",
"properties": {
"_links": {"type": "object"},
"_embedded": {"type": "object"}
}
},
populate_by_name=True # Allows access via both '_links' and 'links'
)