This has been discussed some time ago and Samuel Colvin said he didn't want to pursue this as a feature for Pydantic.

If you are fine with code generation instead of actual runtime creation of models, you can use the datamodel-code-generator.

To be honest, I struggle to see the use case for generating complex models at runtime, seeing as their main purpose is validation, implying that you think about correct schema before running your program. But that is just my view.

For simple models I guess you can throw together your own logic for this fairly quickly.

If do you need something more sophisticated, the aforementioned library does offer some extensibility. You should be able to import and inherit from some of their classes like the JsonSchemaParser. Maybe that will get you somewhere.

Ultimately I think this becomes non-trivial very quickly, which is why Pydantic's maintainer didn't want to deal with it and why there is a whole separate project for this.

Answer from Daniel Fainberg on Stack Overflow
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
By default, the mode is set to 'validation', which produces a JSON schema corresponding to the model's validation schema. The JsonSchemaMode is a type alias that represents the available options for the mode parameter: ... Here's an example of how to specify the mode parameter, and how it affects the generated JSON schema: from decimal import Decimal from pydantic import BaseModel class Model(BaseModel): a: Decimal = Decimal('12.34') print(Model.model_json_schema(mode='validation')) """ { 'properties': { 'a': { 'anyOf': [ {'type': 'number'}, { 'pattern': '^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$', 't
Top answer
1 of 5
11

This has been discussed some time ago and Samuel Colvin said he didn't want to pursue this as a feature for Pydantic.

If you are fine with code generation instead of actual runtime creation of models, you can use the datamodel-code-generator.

To be honest, I struggle to see the use case for generating complex models at runtime, seeing as their main purpose is validation, implying that you think about correct schema before running your program. But that is just my view.

For simple models I guess you can throw together your own logic for this fairly quickly.

If do you need something more sophisticated, the aforementioned library does offer some extensibility. You should be able to import and inherit from some of their classes like the JsonSchemaParser. Maybe that will get you somewhere.

Ultimately I think this becomes non-trivial very quickly, which is why Pydantic's maintainer didn't want to deal with it and why there is a whole separate project for this.

2 of 5
7

Updated @Alon's answer to handle nested modals:

from typing import Any, Type, Optional
from enum import Enum

from pydantic import BaseModel, Field, create_model


def json_schema_to_base_model(schema: dict[str, Any]) -> Type[BaseModel]:
    type_mapping: dict[str, type] = {
        "string": str,
        "integer": int,
        "number": float,
        "boolean": bool,
        "array": list,
        "object": dict,
    }

    properties = schema.get("properties", {})
    required_fields = schema.get("required", [])
    model_fields = {}

    def process_field(field_name: str, field_props: dict[str, Any]) -> tuple:
        """Recursively processes a field and returns its type and Field instance."""
        json_type = field_props.get("type", "string")
        enum_values = field_props.get("enum")

        # Handle Enums
        if enum_values:
            enum_name: str = f"{field_name.capitalize()}Enum"
            field_type = Enum(enum_name, {v: v for v in enum_values})
        # Handle Nested Objects
        elif json_type == "object" and "properties" in field_props:
            field_type = json_schema_to_base_model(
                field_props
            )  # Recursively create submodel
        # Handle Arrays with Nested Objects
        elif json_type == "array" and "items" in field_props:
            item_props = field_props["items"]
            if item_props.get("type") == "object":
                item_type: type[BaseModel] = json_schema_to_base_model(item_props)
            else:
                item_type: type = type_mapping.get(item_props.get("type"), Any)
            field_type = list[item_type]
        else:
            field_type = type_mapping.get(json_type, Any)

        # Handle default values and optionality
        default_value = field_props.get("default", ...)
        nullable = field_props.get("nullable", False)
        description = field_props.get("title", "")

        if nullable:
            field_type = Optional[field_type]

        if field_name not in required_fields:
            default_value = field_props.get("default", None)

        return field_type, Field(default_value, description=description)

    # Process each field
    for field_name, field_props in properties.items():
        model_fields[field_name] = process_field(field_name, field_props)

    return create_model(schema.get("title", "DynamicModel"), **model_fields)

Example Schema

schema = {
    "title": "User",
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"},
        "is_active": {"type": "boolean"},
        "address": {
            "type": "object",
            "properties": {
                "street": {"type": "string"},
                "city": {"type": "string"},
                "zipcode": {"type": "integer"},
            },
        },
        "roles": {
            "type": "array",
            "items": {
                "type": "string",
                "enum": ["admin", "user", "guest"]
            }
        }
    },
    "required": ["name", "age"]
}

Generate the Pydantic model

DynamicModel = json_schema_to_base_model(schema)

Example usage

print(DynamicModel.schema_json(indent=2))
Discussions

Take 2: create model from JSON schema aka model_load_json_schema()
In short, there is a method for ... from JSON to a Model. The use case is simple: I want to give my users the capability to store arbitrary artifacts. An artifact can be anything, any object: a car, a travel trip, a database cluster, a toilet, you name it. But it has to conform to a predefined schema for that object. So an admin user would say, fine, we create the model schema (using the pydantic ... More on github.com
🌐 github.com
5
11
How to define pydantic/JSON schema
Hello, I am working on a text translation project. I extract text from pdf, pass it to gpt-4o-mini and instruct it to translate the text to a target language. The text is in the following format: {‘0’:‘text1’, ‘1’:‘text2’,‘2’:‘text3’, …} I require the output in the ... More on community.openai.com
🌐 community.openai.com
1
1
October 22, 2024
python 3.x - Pydanticv2: How have model_json_schema use definitions instead of $defs? - Stack Overflow
Moving from pydantic v1 to pydanticv2, and need the jsonschema to come out using definitions instead of $defs. Anyone know how to do this natively in pydantic without using string replace? The test More on stackoverflow.com
🌐 stackoverflow.com
New Package: Jambo — Convert JSON Schema to Pydantic Models Automatically
lol, you forgot to remove the intro More on reddit.com
🌐 r/Python
29
76
April 10, 2025
🌐
Medium
medium.com › @kishanbabariya101 › episode-8-json-schema-generation-in-pydantic-9a4c4fee02c8
Episode 8: JSON Schema Generation in Pydantic | by Kishan Babariya | Medium
December 17, 2024 - The model_json_schema() method generates the JSON Schema for a model. ... Field names, types, and constraints. Default values and required fields. FastAPI uses Pydantic’s JSON Schema generation to create interactive API documentation via Swagger ...
🌐
Pydantic
docs.pydantic.dev › latest › concepts › models
Models - Pydantic Validation
See JSON Schema. model_fields: A mapping between field names and their definitions (FieldInfo instances).
Find elsewhere
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › schema
Schema - Pydantic
BaseModel.schema will return a dict of the schema, while BaseModel.schema_json will return a JSON string representation of that dict. Sub-models used are added to the definitions JSON attribute and referenced, as per the spec.
🌐
Reddit
reddit.com › r/python › new package: jambo — convert json schema to pydantic models automatically
r/Python on Reddit: New Package: Jambo — Convert JSON Schema to Pydantic Models Automatically
April 10, 2025 -

🚀 I built Jambo, a tool that converts JSON Schema definitions into Pydantic models — dynamically, with zero config!

What my project does:

  • Takes JSON Schema definitions and automatically converts them into Pydantic models

  • Supports validation for strings, integers, arrays, nested objects, and more

  • Enforces constraints like minLength, maximum, pattern, etc.

  • Built with AI frameworks like LangChain and CrewAI in mind — perfect for structured data workflows

🧪 Quick Example:

from jambo.schema_converter import SchemaConverter

schema = {
    "title": "Person",
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"},
    },
    "required": ["name"],
}

Person = SchemaConverter.build(schema)
print(Person(name="Alice", age=30))

🎯 Target Audience:

  • Developers building AI agent workflows with structured data

  • Anyone needing to convert schemas into validated models quickly

  • Pydantic users who want to skip writing models manually

  • Those working with JSON APIs or dynamic schema generation

🙌 Why I built it:

My name is Vitor Hideyoshi. I needed a tool to dynamically generate models while working on AI agent frameworks — so I decided to build it and share it with others.

Check it out here:

  • GitHub: https://github.com/HideyoshiNakazone/jambo

  • PyPI: https://pypi.org/project/jambo/

Would love to hear what you think! Bug reports, feedback, and PRs all welcome! 😄
#ai #crewai #langchain #jsonschema #pydantic

🌐
Pydantic
docs.pydantic.dev › 2.3 › usage › models
Models - Pydantic
See JSON Schema. model_modify_json_schema(): a method for how the "generic" properties of the JSON schema are populated.
🌐
GitHub
github.com › pydantic › pydantic › issues › 9210
Difference between TypeAdapter().json_schema and BaseModel.model_json_schema · Issue #9210 · pydantic/pydantic
April 11, 2024 - BaseModel.model_json_schema {'properties': {'v': {'key2': 'value2', 'title': 'V', 'type': 'string'}}, # only contains key2 'required': ['v'], 'title': 'Foo', 'type': 'object'} TypeAdapter().json_schema {'key1': 'value1', 'key2': 'value2', 'type': 'string'} # contains key1 and key2 · from pprint import pprint from typing import Annotated from pydantic import TypeAdapter, BaseModel, Field MyStr = Annotated[ str, Field(json_schema_extra={'key1': 'value1'}), Field(json_schema_extra={'key2': 'value2'}) ] class Foo(BaseModel): v: MyStr print("BaseModel.model_json_schema") pprint(Foo.model_json_schema()) print("TypeAdapter().json_schema") pprint(TypeAdapter(MyStr).json_schema())
Author   Mark90
🌐
Pydantic
docs.pydantic.dev › latest › api › base_model
BaseModel - Pydantic Validation
Generates a JSON representation of the model using Pydantic's to_json method. ... model_json_schema( by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, schema_generator: type[ GenerateJsonSchema ] = GenerateJsonSchema, mode: ...
🌐
Pydantic
docs.pydantic.dev › 2.4 › concepts › json_schema
JSON Schema - Pydantic
BaseModel.model_dump_json returns a JSON string representation of the dict of the schema. TypeAdapter.dump_json serializes an instance of the adapted type to JSON. TypeAdapter.json_schema generates a JSON schema for the adapted type. The generated JSON schemas are compliant with the following ...
🌐
GitHub
github.com › google-gemini › deprecated-generative-ai-python › issues › 655
type object 'dummy' has no attribute 'model_json_schema' · Issue #655 · google-gemini/deprecated-generative-ai-python
December 21, 2024 - from pydantic import BaseModel from typing import Optional, TypedDict class Question(BaseModel): # Alternatively, replace with TypedDict for testing question_text: Optional[str] options: list[str] = [""] * 4 correct_option: int exam_section: str class Passage(BaseModel): # Alternatively, replace with TypedDict for testing passage_text: str questions: list[Question] Use the model as response_schema in a call to model.generate_content_async:
Author   thongtr-dev
🌐
Pydantic
docs.pydantic.dev › latest › integrations › datamodel_code_generator
datamodel-code-generator - Pydantic Validation
datamodel-codegen --input person.json --input-file-type jsonschema --output model.py ... { "$id": "person.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "Person", "type": "object", "properties": { "first_name": { "type": "string", "description": "The person's first name."
🌐
PyPI
pypi.org › project › json-schema-to-pydantic
json-schema-to-pydantic · PyPI
2 weeks ago - A Python library for automatically generating Pydantic v2 models from JSON Schema definitions
      » pip install json-schema-to-pydantic
    
Published   Mar 09, 2026
Version   0.4.11