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

从Pydantic V1迁移到V2:如何让model_json_schema使用definitions而非$defs?

Pydantic V2 原生生成含definitions的JSON Schema

要在Pydantic V2中生成使用definitions而非默认$defs的JSON Schema,无需字符串替换,可通过自定义JSON Schema生成器实现:

  1. 自定义JsonSchemaGenerator子类,修改存储引用定义的键名
  2. 调用模型的model_json_schema时指定该生成器,并配合正确的引用模板

完整代码示例

from pydantic import BaseModel, RootModel
from pydantic.json_schema import JsonSchemaGenerator

# 自定义生成器,将默认的$defs替换为definitions
class DefinitionsJsonSchemaGenerator(JsonSchemaGenerator):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.defs_key = "definitions"

# 测试模型
class PropertyReturnStr(BaseModel):
    propertyKey: str
    value: str

class PropertyReturnModel2(RootModel):
    root: list[PropertyReturnStr]

# 生成目标Schema
schema = PropertyReturnModel2.model_json_schema(
    schema_generator=DefinitionsJsonSchemaGenerator,
    ref_template='#/definitions/{model}'
)

# 输出验证
print(schema)

效果说明

生成的JSON Schema会包含"definitions"字段,所有内部引用路径也会指向该字段,完全匹配Pydantic V1的输出格式,且全程为原生实现,无字符串替换操作。

内容的提问来源于stack exchange,提问作者tomvonheill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:34:59