JSON Schema to Pydantic Model Generator
json-schema-to-pydantic is a Python library designed to automatically generate Pydantic v2 models from JSON Schema definitions. It supports complex schema features like references, combiners (allOf, anyOf, oneOf), type constraints, and format validations. The library is actively maintained, with regular updates and improvements, currently at version 0.4.11.
Warnings
- breaking This library is designed exclusively for Pydantic v2 and is not compatible with Pydantic v1 models or schemas. Attempting to use it with Pydantic v1 environments or schemas may lead to unexpected errors.
- gotcha JSON Schema fields starting with underscores (e.g., `_links`, `_embedded`) are common in OpenAPI specifications but are not valid Pydantic field names. By default, these fields might be dropped or cause issues.
- gotcha If your JSON Schema defines a top-level array or scalar type (not an object), directly mapping it to a `BaseModel` might not work as expected in Pydantic v2 without `RootModel`.
- gotcha Schemas with `oneOf` combiners, especially for simple types or references, can lead to incorrect type discrimination or validation issues in older versions.
- gotcha When converting loosely defined JSON schemas (e.g., arrays without `items` schema or fields without a `type`), the generated Pydantic models might be too strict or fail during creation.
Install
-
pip install json-schema-to-pydantic
Imports
- create_model
from json_schema_to_pydantic import create_model
Quickstart
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_data = {"name": "John Doe", "email": "john@example.com", "age": 30}
user = UserModel(**user_data)
print(user.model_dump_json(indent=2))
# Expected output (approx):
# {
# "name": "John Doe",
# "email": "john@example.com",
# "age": 30
# }