JSON Schema to Pydantic Model Converter
jsonschema-pydantic is a Python library that programmatically converts JSON Schemas into Pydantic models, enabling strong data validation and serialization based on schema definitions. Currently at version 0.6, it is actively developed with frequent minor releases to enhance schema feature support and Pydantic version compatibility.
Common errors
-
pydantic.errors.PydanticUserError: Field ... has `init=False` and dataclass has config setting `extra="allow"`. This combination is not allowed.
cause This error typically arises in Pydantic V2 when a Pydantic dataclass (or a BaseModel behaving like one) is configured to allow extra fields but also has fields set with `init=False`. This is a Pydantic-level restriction, which can surface if the `jsonschema-pydantic` generated model's configuration implicitly creates this conflict.fixReview the JSON schema definition for properties that might lead to `init=False` (e.g., complex default factories or computed fields) in conjunction with any `extra_properties` or `additionalProperties` settings in the schema. Adjust the JSON schema or manually modify the generated Pydantic model (if applicable) to remove this conflict. -
pydantic.errors.PydanticUndefinedAnnotation: Name '...' is not defined
cause This error indicates that a type annotation within the generated Pydantic model could not be resolved. This often occurs with circular references in the JSON schema or when a type is referenced before it's fully defined, particularly in complex nested schemas or self-referential structures.fixFor complex nested or circular schemas, Pydantic might require explicit forward references or a `model_rebuild()` call. While `jsonschema-pydantic` handles common cases, for very intricate schemas, you might need to simplify the JSON schema or manually adjust the generated model to include `from typing import ForwardRef` and `Model.model_rebuild()` after all class definitions. -
pydantic.ValidationError: 1 validation error for UserModel...
cause The data provided for validation does not conform to the rules defined in the generated Pydantic model (and thus, the original JSON Schema). Common causes include missing required fields, incorrect data types, or values outside specified constraints (e.g., `minimum`, `maximum`).fixCarefully examine the `ValidationError` message, specifically the `loc` (location) and `msg` (message) fields, to identify which part of your input data violates the schema. Adjust your input data to match the expected structure and constraints defined by the JSON schema.
Warnings
- breaking Pydantic V1 vs V2 Compatibility: While jsonschema-pydantic v0.5.0 introduced backward compatibility for Pydantic V1, Pydantic V2 itself has significant breaking changes. Ensure the Pydantic version installed in your environment matches the expected version for your generated models to avoid runtime issues.
- gotcha JSON Schema 'null' type conversion to Python 'None': As of v0.4.0, the library converts 'null' type in JSON Schema properties to Python's `None` type annotation. Older versions might have handled this differently, potentially leading to discrepancies if relying on specific default behaviors.
- gotcha Schema and Field Descriptions/Titles: Version 0.6.0 improved the incorporation of JSON schema and field descriptions into the generated Pydantic models. For older versions, detailed descriptions or titles might have been ignored, impacting documentation or schema generation fidelity.
Install
-
pip install jsonschema-pydantic
Imports
- jsonschema_to_pydantic
from jsonschema_pydantic import jsonschema_to_pydantic
Quickstart
from jsonschema_pydantic import jsonschema_to_pydantic
json_schema = {
"type": "object",
"properties": {
"name": {"type": "string", "description": "The name of the user"},
"age": {"type": "integer", "minimum": 0},
"email": {"type": "string", "format": "email"}
},
"required": ["name", "age"]
}
# Convert the JSON Schema to a Pydantic model
UserModel = jsonschema_to_pydantic(json_schema, model_name='User')
# Instantiate and validate the generated model
try:
user_data = UserModel(name="Alice", age=30, email="alice@example.com")
print(f"Successfully created user: {user_data.model_dump_json(indent=2)}")
# Example of validation error
invalid_user_data = UserModel(name="Bob", age=-5) # age < minimum
except Exception as e:
print(f"Validation error: {e}")