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

如何基于路径获取JSON Schema属性参数?(Python jsonschema)

解决方案:自定义函数提取JSON Schema参数

Python的jsonschema库本身没有内置的按属性路径提取参数的功能,需要自己实现工具函数来处理schema的各种结构(如properties、additionalProperties、patternProperties等)。以下是一个满足你需求的基础实现:

自定义实现函数

def get_schema_param(schema, path):
    current = schema
    for part in path:
        # 处理对象类型的schema节点
        if current.get("type") == "object":
            # 优先匹配明确定义的properties
            if "properties" in current and part in current["properties"]:
                current = current["properties"][part]
            # 匹配additionalProperties(仅当它是schema对象而非布尔值时)
            elif isinstance(current.get("additionalProperties"), dict):
                current = current["additionalProperties"]
            # 可选:添加patternProperties的正则匹配逻辑
            # elif "patternProperties" in current:
            #     import re
            #     for pattern, prop_schema in current["patternProperties"].items():
            #         if re.fullmatch(pattern, part):
            #             current = prop_schema
            #             break
            #     else:
            #         raise KeyError(f"Path part '{part}' not found in schema")
            else:
                raise KeyError(f"Path part '{part}' not found in schema")
        # 处理非对象类型的节点,直接提取参数
        else:
            if part in current:
                current = current[part]
            else:
                raise KeyError(f"Path part '{part}' not found in schema")
    return current

使用示例

针对你提供的Schema:

schema = {
  "type": "object",
  "properties": {
    "group1": {
      "type": "object",
      "properties": {
        "prop1": {
          "type": "number",
          "minimum": 1000,
          "maximum": 2000
        },
        "prop2": {
          "type": "string",
          "minLength": 2
        }
      }
    }
  },
  "additionalProperties": {
    "type": "number",
    "maximum": 12345,
    "description": "This is an additional property."
  }
}

提取常规属性参数

# 获取prop1的minimum值
val = get_schema_param(schema, ["group1", "prop1", "minimum"])
print(val)  # 输出: 1000

提取额外属性参数

# 获取任意额外属性的description
val = get_schema_param(schema, ["groupXYZ", "description"])
print(val)  # 输出: "This is an additional property."

扩展说明

如果需要支持更复杂的Schema结构(如anyOf、allOf、patternProperties),可以对函数进行扩展:

  • 对于patternProperties:添加正则匹配逻辑,遍历所有正则模式,找到匹配当前路径部分的schema
  • 对于anyOf/allOf:需要根据实际需求决定是遍历所有分支返回第一个匹配的结果,还是返回所有分支的参数集合(这部分逻辑会更复杂,需结合具体场景设计)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:23:14