JSON Schema Pydantic Converter
This library dynamically converts JSON Schema definitions into Pydantic models at runtime. It currently supports both Pydantic v1 and v2. The latest version is 0.4.0, with development actively progressing through minor releases.
Common errors
-
ModuleNotFoundError: No module named 'jsonschema_pydantic'
cause The `jsonschema-pydantic-converter` package is either not installed or not accessible in the current Python environment.fixInstall the package using `pip install jsonschema-pydantic-converter`. -
pydantic.error_wrappers.ValidationError: ... (for Pydantic v1) OR pydantic_core._pydantic_core.ValidationError: ... (for Pydantic v2) occurring during `build_pydantic_model` call.
cause The input `schema_data` dictionary is not a valid JSON Schema or contains constructs that the converter cannot process into a Pydantic model.fixReview the `schema_data` against JSON Schema specification and library's capabilities. Debug the schema's structure and ensure all types and formats are correctly defined. -
AttributeError: 'GeneratedModel' object has no attribute 'model_dump_json'
cause This typically happens when you are using Pydantic v1 (or an environment with v1 installed) but attempting to call Pydantic v2 methods like `model_dump_json` or `model_dump`.fixIf Pydantic v1 is intended, use `.dict()` and `.json()` instead. If Pydantic v2 is required, ensure `pydantic>=2.0` is installed in your environment.
Warnings
- gotcha While the library supports both Pydantic v1 and v2, the behavior of the *generated* models (e.g., method names like `.dict()` vs `.model_dump()`, specific validator implementations) can differ. Ensure your application's Pydantic version aligns with the expected model behavior.
- gotcha The library relies on well-formed and compliant JSON Schema definitions. Malformed schemas, unsupported keywords, or custom extensions not handled by the library can lead to conversion errors or unexpected Pydantic model structures.
- gotcha Schemas with deeply nested or complex `$ref` references, especially those involving circular dependencies or external files, might encounter resolution issues or performance degradation.
Install
-
pip install jsonschema-pydantic-converter
Imports
- build_pydantic_model
from jsonschema_pydantic_converter import build_pydantic_model
from jsonschema_pydantic.builder import build_pydantic_model
Quickstart
from jsonschema_pydantic.builder import build_pydantic_model
# Define a JSON Schema
schema = {
"title": "User",
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"age": {"type": "integer", "minimum": 0, "maximum": 150},
"email": {"type": "string", "format": "email"}
},
"required": ["name", "age"]
}
# Build the Pydantic model from the schema
UserModel = build_pydantic_model(schema_data=schema)
# Instantiate and use the generated model
try:
user_data = UserModel(name="Alice", age=30, email="alice@example.com")
print("Valid user data:")
print(user_data.model_dump_json(indent=2))
except Exception as e:
print(f"Error creating valid user: {e}")
# Demonstrate validation failure
try:
invalid_user_data = UserModel(name="", age=-5)
print("Invalid user data (should not reach here):", invalid_user_data)
except Exception as e:
print("\nValidation error for invalid user data:")
print(e)