JSON Schema合并多个$ref时设置additionalProperties=false报错如何解决?
问题根源
你现在的写法存在两个核心错误:
allOf是JSON Schema的组合关键字,需要和type、additionalProperties同级,不能放在properties字段内部。你当前把allOf写在properties里,相当于声明了一个名为allOf的合法属性,而不是合并两个引用的属性定义,因此name、age都不会被识别为合法属性。- 你的
blue.json和red.json的definition结构不符合JSON Schema规范,直接写属性集合不会被识别为合法的对象属性定义,需要套在properties字段内。
解决方案
方案1:使用unevaluatedProperties(适配JSON Schema Draft 2019-09及以上版本)
additionalProperties的作用范围仅为当前schema下properties和patternProperties中声明的字段,无法识别allOf等组合关键字引入的属性。如果你的校验工具支持新版JSON Schema规范,可以用unevaluatedProperties代替,它会遍历所有组合schema中声明的属性,仅禁止未在任何子schema中声明的字段。
首先修正子schema结构:
// blue.json { "definition": { "properties": { "name": { "type": "string" } } } }
// red.json { "definition": { "properties": { "age": { "type": "string" } } } }
再修改主schema:
{ "type": "object", "unevaluatedProperties": false, "allOf": [ { "$ref": "type/blue.json#/definition" }, { "$ref": "type/red.json#/definition" } ] }
方案2:兼容低版本JSON Schema(Draft 7及更早)
如果校验工具不支持新版规范,可以在当前schema的properties中显式声明所有允许的属性名,即可让additionalProperties正常识别:
{ "type": "object", "additionalProperties": false, // 显式声明所有允许的属性名,值设为true即可继承allOf中的校验规则 "properties": { "name": true, "age": true }, "allOf": [ { "$ref": "type/blue.json#/definition" }, { "$ref": "type/red.json#/definition" } ] }
内容的提问来源于stack exchange,提问作者Samuel Da Costa
相关产品推荐
相关产品推荐

