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

如何用JSON Schema动态校验default值匹配options属性?

当然可以用JSON Schema实现这个动态校验

完全能做到!你可以借助JSON Schema的dependencies配合enum和$data关键字(注意:$data是JSON Schema Draft 6及以上的扩展特性,Ajv这类主流校验库都支持)来实现需求。

对应的校验Schema示例

针对你提供的JSON结构,具体的校验Schema如下:

{
  "type": "object",
  "properties": {
    "top": {
      "type": "object",
      "properties": {
        "label": { "type": "string" },
        "default": { "type": "string" },
        "options": {
          "type": "object",
          "additionalProperties": {
            "type": "object",
            "properties": { "label": { "type": "string" } },
            "required": ["label"]
          }
        }
      },
      "required": ["label", "default", "options"],
      "dependencies": {
        "default": {
          "properties": {
            "default": {
              "$data": "#/top/options",
              "enum": { "$data": "0#" }
            }
          }
        }
      }
    }
  },
  "required": ["top"]
}

核心逻辑解释

  • $data用来动态引用实例里的具体值:"$data": "#/top/options"指向options对象,"enum": { "$data": "0#" }会自动提取该对象的所有属性键,作为default值的可选枚举范围。
  • dependencies规则保证只要default字段存在,它的值就必须在options的属性键列表里。

如果你的校验工具不支持$data,也可以通过自定义校验逻辑实现,但$data是最简洁的原生解决方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 23:28:17