JSON Schema 如何实现条件性新增key3属性的校验规则
错误原因
JSON Schema 中 additionalProperties: false 的校验逻辑仅识别当前层级 properties 节点显式声明的字段。你将 key3 的定义放在了 then 条件分支内,顶层 properties 没有声明 key3,因此即使满足触发 then 的条件,顶层的 additionalProperties 仍会将 key3 判定为非法额外字段直接拦截,导致报错。
正确实现方案
方案1:兼容 Draft-07 版本
调整逻辑,先在顶层声明所有可能出现的字段,再通过分支逻辑控制 key3 是否允许出现:
{ "$async": true, "additionalProperties": false, "properties": { "key1": { "type": "string" }, "key2": { "type": "string" }, "key3": { "type": "string" } }, "required": ["key1"], "allOf": [ { "if": { "properties": { "key1": { "const": "value1" }, "key2": { "const": "value2" } }, "required": ["key1", "key2"] }, "then": { "required": ["key3"] }, "else": { "not": { "required": ["key3"] } } } ] }
逻辑说明:
- 顶层提前声明所有合法字段,配合
additionalProperties: false禁止所有未声明的额外字段 if分支新增required: ["key1", "key2"],确保只有两个字段同时存在且值匹配时才触发后续逻辑- 满足条件时强制要求携带
key3,不满足条件时禁止携带key3
方案2:Draft 2019-09 及以上版本简化实现
使用 unevaluatedProperties 替代 additionalProperties,该配置会自动识别所有分支内声明的字段:
{ "$async": true, "$schema": "https://json-schema.org/draft/2019-09/schema", "unevaluatedProperties": false, "properties": { "key1": { "type": "string" }, "key2": { "type": "string" } }, "required": ["key1"], "allOf": [ { "if": { "properties": { "key1": { "const": "value1" }, "key2": { "const": "value2" } }, "required": ["key1", "key2"] }, "then": { "properties": { "key3": { "type": "string" } }, "required": ["key3"] }, "else": { "properties": { "key3": false } } } ] }
内容的提问来源于stack exchange,提问作者Ganesh Satpute
相关产品推荐
相关产品推荐

