JSON Schema如何为含任意键的数组项设置additionalProperties: false校验
解决方案
你当前的校验规则不生效,核心原因是对转换后的数据结构层级判断错误:待校验的YAML转JSON后,MyArray的每个数组项本身是仅包含1个随机名称键的对象,你要求的one/two/three是这个随机键对应的值的属性,而非数组项对象自身的属性。
调整后的校验规则
"MyArray": { "type": "array", "items": { "type": "object", "minProperties": 1, "maxProperties": 1, "patternProperties": { ".*": { "type": "object", "additionalProperties": false, "required": [ "one", "two", "three" ], "properties": { "one": { "type": "string" }, "two": { "type": "string" }, "three": { "type": "string" } } } }, "additionalProperties": false } }
规则说明
minProperties: 1+maxProperties: 1:强制每个数组项有且仅有1个顶层随机键,不会出现空对象或者多个顶层键的非法情况patternProperties:匹配任意名称的顶层键,要求该键对应的值必须符合你预设的one/two/three结构规则- 内层的
additionalProperties: false:禁止one/two/three之外的字段出现在实际的内容对象中,完全满足你的校验需求
内容的提问来源于stack exchange,提问作者red888
相关产品推荐
相关产品推荐

