JSON Schema列表场景下If/then/else逻辑失效,条件必填校验异常求助
JSON Schema条件必填校验问题解决
问题出在你的Schema逻辑没有正确区分两种场景的必填规则,大概率是把paymentRef1放到了全局required数组里,或者条件分支的排除逻辑错误,导致无论paymentType是什么,都在校验paymentRef1的必填性。
用JSON Schema的if/then/else结构可以精准实现你的需求,示例如下:
{ "type": "object", "properties": { "paymentType": { "type": "string" }, "paymentRef1": { "type": "string" }, "otherRequiredProp1": { "type": "string" }, "otherRequiredProp2": { "type": "string" } // 其他属性定义补充在这里 }, "allOf": [ { "if": { "properties": { "paymentType": { "const": "Shopping_cards" } }, "required": ["paymentType"] }, "then": { "required": ["paymentRef1"] }, "else": { "required": ["otherRequiredProp1", "otherRequiredProp2"] // 这里替换成你需要的其他必填属性 } } ] }
关键说明:
- 全局
required列表不要包含paymentRef1或其他条件必填的属性,完全交给条件分支控制 if块先匹配paymentType为Shopping_cards的情况,then块指定此时必填paymentRef1else块处理所有paymentType不等于Shopping_cards的场景,指定对应的必填属性- 确保你的校验器支持JSON Schema draft-07及以上版本(
if/then/else从该版本开始支持)
内容的提问来源于stack exchange,提问作者Loren
相关产品推荐
相关产品推荐

