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

如何基于父JSON Schema属性值校验子Schema同名属性取值一致性

错误点修正

你原来的写法有两个核心错误:

  • if/then 是JSON Schema的顶级条件关键字,不需要嵌套在dependentSchemas下,dependentSchemas仅用于「指定属性存在时才触发对应校验」的场景,和你的需求不匹配
  • 原Schema存在语法问题:order.id的类型定义错误,缺少type关键字包裹

正确的Schema实现

{
  "type": "object",
  "properties": {
    "action": {
      "enum": ["get", "post"]
    },
    "order": {
      "type": "object",
      "properties": {
        "id": {
          "type": "string"
        },
        "action": {
          "enum": ["get", "post"]
        }
      },
      "required": ["id", "action"]
    }
  },
  "required": ["action", "order"],
  "if": {
    "properties": {
      "action": { "const": "get" }
    }
  },
  "then": {
    "properties": {
      "order": {
        "properties": {
          "action": { "const": "get" }
        }
      }
    }
  },
  "else": {
    "properties": {
      "order": {
        "properties": {
          "action": { "const": "post" }
        }
      }
    }
  }
}

如果你后续会扩展action的枚举值,不想每次都新增条件分支,也可以用JSON Schema的$data关键字(需要确认你使用的jsonschema库支持该特性,主流库如Python的jsonschema、前端的Ajv都兼容),写法更简洁:

{
  "type": "object",
  "properties": {
    "action": {
      "enum": ["get", "post"]
    },
    "order": {
      "type": "object",
      "properties": {
        "id": {
          "type": "string"
        },
        "action": {
          "const": { "$data": "/action" }
        }
      },
      "required": ["id", "action"]
    }
  },
  "required": ["action", "order"]
}

校验效果验证

注:你提供的测试用例存在JSON语法错误,id属性定义后缺少逗号,校验前需要先修正。

  • 修正后的正向用例可以正常通过校验
  • 修正后的反向用例会触发action取值不匹配的校验错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:57:03