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

复杂多数组JSON Schema中anyOf匹配规则验证问题求助

JSON Schema验证:至少存在一个指定名称的子节点

输入JSON

{
  "grandParent": {
    "parent1": {
      "kids": [{
        "name": "David"
      }, {
        "name": "Josh"
      }]
    },
    "parent2": {
      "kids": [{
        "name": "Michael"
      }]
    }
  }
}

需求

编写JSON Schema,当JSON中**至少有一个孩子(无论属于哪个父节点)**的name为"David"或"Kevin"时验证通过。

尝试的Schema(存在问题)

{
  "properties": {
    "grandParent": {
      "additionalProperties": {
        "properties": {
          "kids": {
            "type": "array",
            "contains": {
              "properties": {
                "name": {
                  "anyOf": [
                    {
                      "type": "string",
                      "pattern": "David"
                    },
                    {
                      "type": "string",
                      "pattern": "Kevin"
                    }
                  ]
                }
              }
            }
          }
        }
      }
    }
  }
}

问题原因

这个Schema错误地要求所有父节点的kids数组都必须包含name为"David"或"Kevin"的孩子。additionalProperties关键字会对grandParent下的每一个属性(比如parent1、parent2)都应用内部的验证规则,因此parent2的kids不符合条件时就会触发报错,而忽略了parent1已经满足需求的情况。

正确的Schema

{
  "properties": {
    "grandParent": {
      "type": "object",
      // 确保grandParent下至少有一个父节点满足条件
      "contains": {
        "properties": {
          "kids": {
            "type": "array",
            // 检查当前父节点的kids数组中存在指定name的孩子
            "contains": {
              "properties": {
                "name": {
                  "enum": ["David", "Kevin"]
                }
              },
              "required": ["name"]
            }
          }
        },
        "required": ["kids"]
      }
    }
  },
  "required": ["grandParent"]
}

说明

  1. grandParent层级使用contains关键字:确保该对象下至少有一个属性值(即某个父节点)符合内部的验证规则。
  2. 内部的contains用于检查父节点的kids数组中存在name为"David"或"Kevin"的元素。
  3. 使用enum替代anyOf+pattern更直接,因为是精确匹配指定字符串。
  4. 添加required关键字确保必要的字段存在,避免因缺失字段导致的误判。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:35:20