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

如何在JSON Schema中实现基于name字段的条件数组验证?

实现方案说明

完全可行,无需拆分验证逻辑,利用JSON Schema的if/then/else条件分支,结合required、contains、enum等关键字即可实现需求。

完整JSON Schema示例

{
  "type": "object",
  "required": ["name", "lines"],
  "properties": {
    "name": { "type": "string", "enum": ["one", "two"] },
    "lines": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["id"],
        "properties": {
          "id": { "type": "string" },
          "foo": {
            "type": "object",
            "required": ["type"],
            "properties": {
              "type": { "type": "string", "enum": ["abc", "xyz"] }
            }
          }
        },
        "additionalProperties": false
      }
    }
  },
  "if": {
    "properties": { "name": { "const": "one" } }
  },
  "then": {
    "properties": {
      "lines": {
        "items": {
          "maxProperties": 1,
          "required": ["id"]
        }
      }
    }
  },
  "else": {
    "properties": {
      "lines": {
        "minItems": 1,
        "contains": {
          "required": ["foo"],
          "properties": {
            "foo": {
              "not": { "properties": { "type": { "enum": [] } } }
            }
          }
        }
      }
    }
  }
}

关键逻辑解释

  • 基础约束:定义必填字段name和lines,name仅允许"one"或"two";lines数组元素默认强制包含id字段,且不允许额外未定义字段(additionalProperties: false)。
  • 当name为"one"时:通过then分支限制lines的每个元素最多只能有1个字段(maxProperties:1),确保仅保留必填的id。
  • 当name为"two"时:通过else分支要求lines至少有1个元素(minItems:1),且数组中至少存在一个元素包含非空的foo字段,同时foo.type必须是"abc"或"xyz"(依赖foo字段预定义的enum约束)。

Ajv使用提示

上述Schema基于JSON Schema Draft 7标准,Ajv v8及以上版本可直接支持,无需额外配置。若使用旧版Ajv,需确保启用对应Draft版本的支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:45:37