如何在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
相关产品推荐
相关产品推荐

