You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在运行时从JSON动态构建Pydantic模型(无需代码生成器)

运行时动态构建Pydantic验证器的方法

完全可以无需代码生成器,在运行时动态构建Pydantic验证模型,下面是两种实用的实现方案:

方案1:用Pydantic内置create_model手动转换JSON Schema

Pydantic自带的create_model函数支持在运行时生成模型,我们可以将JSON Schema的字段规则转换成该函数所需的参数格式,直接构建验证器。

from pydantic import create_model, Field
from typing import Any

validator_description = {
    "$id": "person.json",
    "title": "Person",
    "type": "object",
    "properties": {
        "first_name": {"type": "string", "description": "The person's first name."},
        "last_name": {"type": "string", "description": "The person's last name."},
        "age": {"description": "Age in years.", "type": "integer", "minimum": 0},
    },
    "required": ["first_name", "last_name"]
}

# 转换JSON Schema字段为Pydantic字段定义
field_definitions = {}
type_mapping = {"string": str, "integer": int, "number": float, "boolean": bool}

for field_name, props in validator_description["properties"].items():
    # 匹配基础类型
    field_type = type_mapping.get(props["type"], Any)
    # 提取验证规则和描述
    field_kwargs = {}
    if "description" in props:
        field_kwargs["description"] = props["description"]
    if "minimum" in props:
        field_kwargs["ge"] = props["minimum"]
    # 必填字段设置默认值为...表示必填
    if field_name in validator_description.get("required", []):
        field_definitions[field_name] = (field_type, Field(**field_kwargs))
    else:
        field_definitions[field_name] = (field_type, Field(None, **field_kwargs))

# 动态生成模型
Person = create_model(validator_description["title"], **field_definitions)

# 验证合法数据
valid_data = {"first_name": "John", "last_name": "Doe", "age": 25}
person = Person(**valid_data)
print(person)  # first_name='John' last_name='Doe' age=25

# 验证非法数据(年龄为负)
invalid_data = {"first_name": "John", "last_name": "Doe", "age": -5}
try:
    Person(**invalid_data)
except Exception as e:
    print(e)  # 1 validation error for Person
              # age
              #   Input should be greater than or equal to 0 [type=greater_than_equal, input_value=-5, input_type=int]

方案2:基于JSON Schema直接解析生成模型(Pydantic v2+)

Pydantic v2提供了JSON Schema转模型的工具函数,可以更便捷地直接从Schema描述生成验证模型:

from pydantic import create_model
from pydantic.json_schema import from_json_schema

validator_description = {
    "$id": "person.json",
    "title": "Person",
    "type": "object",
    "properties": {
        "first_name": {"type": "string", "description": "The person's first name."},
        "last_name": {"type": "string", "description": "The person's last name."},
        "age": {"description": "Age in years.", "type": "integer", "minimum": 0},
    },
    "required": ["first_name", "last_name"]
}

# 将JSON Schema转换为Pydantic可识别的字段定义
parsed_schema = from_json_schema(validator_description)
# 动态创建模型
Person = create_model(
    validator_description["title"],
    **parsed_schema["properties"],
    __config__=None
)

# 使用验证器
data = {"first_name": "John", "last_name": "Doe", "age": 30}
person = Person(**data)
print(person.model_dump_json(indent=2))

关键说明

  • 动态生成的模型和静态定义的模型功能完全一致,支持验证、序列化、字段文档等所有Pydantic特性。
  • 对于嵌套对象、数组、枚举等复杂Schema结构,只需扩展类型映射或依赖from_json_schema的自动解析能力即可处理。
  • Pydantic v1版本可以使用pydantic.SchemaModel类实现类似的动态加载功能。

内容的提问来源于stack exchange,提问作者Mehdi Ben Hamida

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:57:44