JSON Schema如何基于布尔值设置条件并通过additionalProperties:false做字段限制
问题根源
你原有Schema的核心问题有两个:
- 顶层
required列表强制要求user_email_list、host_info必须存在,和send_notifications: false时不需要这两个字段的需求冲突 - 未实现基于
send_notifications取值的分支校验逻辑,也没有限制send_notifications: false时不能出现额外字段
完整可运行Schema
{ "$schema": "http://json-schema.org/draft-07/schema", "type": "object", "required": [ "capture_state", "send_notifications" ], "properties": { "capture_state": { "type": "string" }, "send_notifications": { "type": "boolean" }, "user_email_list": { "type": "array", "items": { "type": "string", "format": "email" } }, "host_info": { "type": "array", "items": { "type": "object", "required": [ "ansible_host", "ECRTicket" ], "properties": { "ansible_host": { "type": "string" }, "ECRTicket": { "type": "string" } }, "additionalProperties": false } } }, "additionalProperties": false, "allOf": [ { "if": { "properties": { "send_notifications": { "const": true } }, "required": ["send_notifications"] }, "then": { "required": ["user_email_list", "host_info"] }, "else": { "not": { "anyOf": [ {"required": ["user_email_list"]}, {"required": ["host_info"]} ] } } } ] }
注:已优化原有代码中冗余的
anyOf嵌套写法,不影响原有校验逻辑。
逻辑拆解
- 公共规则:所有合法结构必须包含
capture_state、send_notifications字段,不允许出现schema未定义的额外字段,四个字段的类型校验统一在顶层properties定义(避免additionalProperties: false将分支字段识别为非法字段) - 分支规则:
- 当
send_notifications为true时,强制要求user_email_list、host_info必须存在 - 当
send_notifications为false时,强制要求不能出现user_email_list、host_info字段
- 当
校验效果验证
- 合法输入1:
send_notifications为true,同时包含四个字段,校验通过 - 合法输入2:
send_notifications为false,仅包含两个公共字段,校验通过 - 非法输入1:
send_notifications为true,缺少user_email_list或host_info,校验失败 - 非法输入2:
send_notifications为false,携带user_email_list或host_info,校验失败 - 非法输入3:携带除四个定义字段外的其他自定义字段,校验失败
内容的提问来源于stack exchange,提问作者JrOpsEngineer
相关产品推荐
相关产品推荐

