如何消除JSON Schema中oneOf校验的枚举误报错误
问题:JSON Schema oneOf校验出现误报,如何避免?
我用JSON Schema的oneOf关键字校验JSON数据,校验工具能捕获真实错误“整数-5小于最小值0”,但同时会弹出误报:“值"Test12"未在枚举中定义”。我希望只有在校验不通过时显示真实错误,校验通过时无任何错误提示。
原JSON Schema
{ "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "object", "properties": { "eventName": { "type": "string", "enum": ["Test10", "Test12", "Test1", "Test2", "Test3"] }, "eventPayload": { "type": "object", "properties": { "totalAmount": { "type": "number" } } } }, "oneOf": [ { "properties": { "eventName": { "enum": ["Test10", "Test12"] }, "eventPayload": { "properties": { "totalAmount": { "exclusiveMinimum": 0 } } } } }, { "properties": { "eventName": { "enum": ["Test1", "Test2", "Test3"] }, "eventPayload": { "properties": { "totalAmount": { "exclusiveMaximum": 0 } } } } } ] }
待校验JSON数据
{ "eventName": "Test12", "eventPayload": { "totalAmount": -5 } }
当前错误信息
Message: Value "Test12" is not defined in enum. Schema path: #/oneOf/1/properties/eventName/enum Message: Integer -5 is less than minimum value of 0. Schema path: #/oneOf/0/properties/eventPayload/properties/totalAmount/minimum
解决方案
问题根源在于oneOf的子Schema未做条件限制:校验工具会遍历所有oneOf分支,即使当前eventName不属于该分支的枚举范围,仍会校验分支内的所有规则,从而产生误报。
修正思路是用if/then条件校验替代原有的直接属性定义,让每个oneOf分支仅在eventName匹配对应枚举时,才校验totalAmount的规则;若eventName不匹配,该分支自动通过校验,不会触发错误。
修正后的JSON Schema
{ "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "object", "properties": { "eventName": { "type": "string", "enum": ["Test10", "Test12", "Test1", "Test2", "Test3"] }, "eventPayload": { "type": "object", "properties": { "totalAmount": { "type": "number" } } } }, "oneOf": [ { "if": { "properties": { "eventName": { "enum": ["Test10", "Test12"] } }, "required": ["eventName"] }, "then": { "properties": { "eventPayload": { "properties": { "totalAmount": { "exclusiveMinimum": 0 } }, "required": ["totalAmount"] // 若totalAmount为必填项则保留,否则可移除 } } } }, { "if": { "properties": { "eventName": { "enum": ["Test1", "Test2", "Test3"] } }, "required": ["eventName"] }, "then": { "properties": { "eventPayload": { "properties": { "totalAmount": { "exclusiveMaximum": 0 } }, "required": ["totalAmount"] // 若totalAmount为必填项则保留,否则可移除 } } } } ] }
效果说明
- 当待校验数据的
eventName为Test12时,仅会触发第一个oneOf分支的then规则校验,捕获totalAmount=-5的错误;第二个分支因if条件不满足,直接通过校验,不会产生误报。 - 若数据完全符合规则(如
eventName="Test12"且totalAmount=10),则无任何错误提示。
内容的提问来源于stack exchange,提问作者Loren
相关产品推荐
相关产品推荐

