JSON Schema子对象条件约束验证失效问题咨询
JSON Schema条件验证问题排查与修复
问题场景
原始JSON Schema
{ "type":"object", "properties":{ "a":{ "type":"number", "minimum":1, "maximum":2 }, "b":{ "type":"object", "properties":{ "c":{"type": "number"} }, "required":[ "c" ], "additionalProperties":false } }, "required":[ "a", "b" ], "additionalProperties":false, "if":{ "properties":{ "a":{ "const":1 } } }, "then":{ "properties":{ "b":{ "d":{"type":"number"}, "required":[ "c", "d" ] } } }, "else":{ "properties":{ "b":{ "e":{"type":"number"}, "required":[ "c", "e" ] } } } }
预期匹配实例
- 当
a=1时:
{ "a": 1, "b": { "c": 1, "d": 1 } }
- 当
a=2时:
{ "a": 2, "b": { "c": 1, "e": 1 } }
预期拒绝实例
{ "a": 2, "b": { "c": 1, "d": 1 } }
实际验证错误
验证第一个预期匹配实例时,收到错误:Property 'd' has not been defined and the schema does not allow additional properties
问题原因
主Schema中b属性的additionalProperties: false会对所有情况生效,包括if-then触发的场景。虽然then块给b添加了d的属性定义和必填要求,但没有将d合并到b的properties列表中——主Schema的b.properties只有c,所以验证器会认为d是未定义的额外属性,触发报错。
JSON Schema的if-then-else是对整个实例添加额外约束,不会自动覆盖或合并主Schema中已有的属性约束。
修复方案
在then和else块中,重新完整定义b的Schema:包含原有c属性、新增的d/e属性,同时保留additionalProperties: false,确保所有允许的属性都被明确声明。
修正后的JSON Schema
{ "type":"object", "properties":{ "a":{ "type":"number", "minimum":1, "maximum":2 }, "b":{ "type":"object", "properties":{ "c":{"type": "number"} }, "required":[ "c" ], "additionalProperties":false } }, "required":[ "a", "b" ], "additionalProperties":false, "if":{ "properties":{ "a":{ "const":1 } } }, "then":{ "properties":{ "b":{ "type":"object", "properties":{ "c":{"type": "number"}, "d":{"type":"number"} }, "required":[ "c", "d" ], "additionalProperties":false } } }, "else":{ "properties":{ "b":{ "type":"object", "properties":{ "c":{"type": "number"}, "e":{"type":"number"} }, "required":[ "c", "e" ], "additionalProperties":false } } } }
验证说明
修正后:
a=1时,b允许c和d,且两者必填,拒绝其他额外属性a=2时,b允许c和e,且两者必填,拒绝其他额外属性- 完全符合预期的匹配与拒绝规则
内容的提问来源于stack exchange,提问作者Raven
相关产品推荐
相关产品推荐

