如何在JSON Schema中根据另一个属性值定义关联对象
JSON Schema实现属性值关联校验
可以实现你需要的属性值关联校验,核心是用oneOf结合if/then关键字(JSON Schema Draft 07及以上版本支持),或者直接在oneOf分支中定义完整的场景约束,替代原来的松散校验逻辑。
方案一:使用if/then分支约束
这种方式更清晰,保留原有properties结构的同时,通过条件判断绑定channelName和channelDetails的对应关系:
{ "type": "object", "properties": { "channelName": { "type": "string", "enum": ["channel_type_A", "channel_type_B"] }, "channelDetails": { "type": "object" } }, "required": ["channelName", "channelDetails"], "oneOf": [ { "if": { "properties": { "channelName": { "const": "channel_type_A" } } }, "then": { "properties": { "channelDetails": TYPE_A } } }, { "if": { "properties": { "channelName": { "const": "channel_type_B" } } }, "then": { "properties": { "channelDetails": TYPE_B } } } ] }
required确保两个属性必须存在oneOf保证只能匹配其中一个分支的约束- 每个分支通过
if判断channelName的取值,then强制channelDetails必须符合对应的TYPE_A/TYPE_B结构
方案二:直接定义完整场景结构
如果不需要保留外层的properties结构,也可以直接在oneOf中定义每个合法场景的完整对象约束:
{ "type": "object", "oneOf": [ { "properties": { "channelName": { "const": "channel_type_A" }, "channelDetails": TYPE_A }, "required": ["channelName", "channelDetails"], "additionalProperties": false }, { "properties": { "channelName": { "const": "channel_type_B" }, "channelDetails": TYPE_B }, "required": ["channelName", "channelDetails"], "additionalProperties": false } ] }
- 每个分支直接限定channelName的固定值和对应的channelDetails结构
additionalProperties: false可以限制对象不能包含其他未定义的属性(根据需求可选)
关于dependencies的说明
你提到的dependencies关键字确实主要用于校验属性是否存在的依赖关系,无法直接实现基于属性值的关联约束,因此上述两种方案是更合适的选择。
内容的提问来源于stack exchange,提问作者Silvia di Luise
相关产品推荐
相关产品推荐

