如何基于其他对象键值设置JSON Schema条件必填字段?
基于其他对象字段的JSON Schema条件必填实现
要实现当a.key2为true时b.key4必填,否则可选的逻辑,你可以利用JSON Schema的根级if/then/else关键字来跨对象关联条件判断。以下是完整的Schema示例:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "a": { "type": "object", "properties": { "key1": { "type": "string" }, "key2": { "type": "boolean" } }, "required": ["key1", "key2"] // 可根据实际需求调整a的必填字段 }, "b": { "type": "object", "properties": { "key3": { "type": "string" }, "key4": { "type": "string" } }, "required": ["key3"] // key3始终为必填字段 } }, "required": ["a", "b"], // 可根据实际需求调整根对象的必填属性 "if": { "properties": { "a": { "properties": { "key2": { "const": true } } } } }, "then": { "properties": { "b": { "required": ["key3", "key4"] // 满足条件时,b.key4变为必填 } } }, "else": { "properties": { "b": { "required": ["key3"] // 不满足条件时,b.key4保持可选 } } } }
关键逻辑说明:
if块:在根层级检查a.key2是否精确等于true,通过const关键字实现严格匹配。then块:当if的条件成立时,覆盖b对象的required配置,强制key4成为必填项。else块:当if的条件不成立时,恢复b对象的基础必填规则,key4自动变为可选。
注意:该方案依赖JSON Schema Draft 07及以上版本的if/then/else特性,确保你的验证工具支持对应版本。
内容的提问来源于stack exchange,提问作者Allen Wang
相关产品推荐
相关产品推荐

