Ajv开启strict模式下anyOf搭配required的JSON Schema校验失败如何解决
问题根因
该报错由Ajv的strictRequired严格校验规则触发:规则要求所有在required数组中声明的必填属性,必须在同一个schema对象的properties字段下明确定义。目前Ajv不会跨schema分支(如anyOf子项)继承父级的properties定义做校验,属于Ajv的已知实现限制。
修复方案
方案1:仅调整编译参数(无需修改Schema)
保留你原有Schema的写法,在编译命令中单独关闭strictRequired校验即可,既不影响其他strict规则的生效,也能绕过本次误报:
ajv compile --spec=draft2020 --validate-formats=true --verbose --all-errors --strict=true --strict-required=false -c ajv-formats -s repro.json
方案2:调整Schema写法适配Strict模式
你之前把properties移入anyOf子项后功能不符合预期,是因为你用了additionalProperties: false——该关键字只会识别同层级和父级schema中定义的属性,不会识别anyOf/allOf/oneOf等分支内的属性。
你可以将additionalProperties: false替换为Draft 2019及以上规范支持的unevaluatedProperties: false,该关键字会识别所有分支内定义的属性,完全符合你的需求。修复后的完整Schema如下:
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$ref": "#/$defs/root", "$defs": { "root": { "type": "object", "unevaluatedProperties": false, "anyOf": [ { "properties": { "alpha": { "$ref": "#/$defs/alpha" }, "beta": { "$ref": "#/$defs/beta" } }, "required": ["alpha"] }, { "properties": { "alpha": { "$ref": "#/$defs/alpha" }, "beta": { "$ref": "#/$defs/beta" } }, "required": ["beta"] } ] }, "alpha": { "type": "object", "additionalProperties": false, "properties": { "foo": { "type": "string" } } }, "beta": { "type": "object", "additionalProperties": false, "properties": { "bar": { "type": "string" } } } } }
修复后的Schema可以正常通过strict模式校验,同时完全满足需求:
- 对象至少包含alpha、beta中的任意一个属性
- 不允许出现未定义的额外属性
- alpha、beta的结构校验规则保持不变
内容的提问来源于stack exchange,提问作者beatcracker
相关产品推荐
相关产品推荐

