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

基于Label值的JSON Schema数组对象匹配验证问题求助

解决方案

你需要针对数组中的每个元素单独设置条件验证,而非对整个数组做包含判断。核心思路是在props的items里用if/then关键字,为不同label值的对象指定专属验证规则:

{
  "type": "object",
  "properties": {
    "props": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "label": { "type": "string" },
          "attributes": { "type": "object" }
        },
        "required": ["label", "attributes"],
        // 验证Residential类型的对象
        "if": {
          "properties": {
            "label": { "const": "Residential" }
          },
          "required": ["label"]
        },
        "then": {
          "properties": {
            "attributes": {
              "required": ["housingStatus"],
              "properties": {
                "housingStatus": { "const": "Own" }
              }
            }
          }
        },
        // 验证Communication类型的对象
        "if": {
          "properties": {
            "label": { "const": "Communication" }
          },
          "required": ["label"]
        },
        "then": {
          "properties": {
            "attributes": {
              "required": ["canContact"],
              "properties": {
                "canContact": { "const": "Yes" }
              }
            }
          }
        }
      }
    }
  },
  "required": ["props"]
}

关键细节

  • 把条件逻辑放在items内部,确保每个数组元素独立检查,不会误影响其他元素。
  • 用const精准匹配label值,比pattern更简洁高效。
  • 每个if/then块仅对对应label的对象生效,其他label的对象只要满足基础结构(含label和attributes字段)即可,不受特定规则约束。后续新增其他label的验证规则,直接加新的if/then块就行。

验证结果

  • 若label为Residential,必须包含attributes.housingStatus且值为Own,否则验证失败。
  • 若label为Communication,必须包含attributes.canContact且值为Yes,否则验证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:23:33