JSON Schema to Pydantic Model Converter

0.6 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

Demonstrates how to define a JSON Schema, convert it into a Pydantic model using `jsonschema_to_pydantic`, and then use the generated model for data validation and instantiation. This example also shows how schema properties like 'description' and 'minimum' are translated to Pydantic model fields and validations.

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}")

view raw JSON →