JSON Schema Pydantic Converter

0.4.0 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple JSON Schema, use `build_pydantic_model` to generate a Pydantic model dynamically, and then instantiate and validate data against the newly created model. It also shows an example of a validation failure.

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)

view raw JSON →