如何使用if/then/else实现JSON Schema依赖属性的对象/null条件校验
问题原因
你编写的Schema存在两个核心问题导致校验不生效:
- 错误使用
topObj.ineligibleReason这种点路径作为properties的键,JSON Schema的properties仅识别当前校验层级的属性名,不支持跨层级路径写法 - else分支的
myObject规则写在了根Schema层级,实际该属性隶属于topObj下,规则完全未命中
正确Schema配置
推荐将条件判断写到topObj的Schema定义内部,避免层级混淆,完整代码如下,兼容Postman内置的AJV校验规则:
{ "type": "object", "properties": { "topObj": { "type": "object", "properties": { "subItem1": { "type": "string" }, "subItem2": { "type": "string" }, "ineligibleReason": { "type": "string" }, "myObject": { "type": ["object", "null"] } }, "required": ["subItem1", "subItem2", "ineligibleReason", "myObject"], "additionalProperties": false, // 条件判断直接写在topObj层级下,直接引用当前层级属性即可 "if": { "properties": { "ineligibleReason": { "const": "" } }, "required": ["ineligibleReason"] }, "then": { "properties": { "myObject": { "type": "object", "properties": { "subObject1": { "type": "boolean" }, "subObject2": { "type": "string" } }, "required": ["subObject1", "subObject2"], "additionalProperties": false } } }, "else": { "properties": { "myObject": { "type": "null" } } } } }, "required": ["topObj"], "additionalProperties": false }
校验逻辑说明
- 当
ineligibleReason为空字符串时,触发then规则,要求myObject必须是包含指定子属性的对象,为null会校验失败 - 当
ineligibleReason为非空字符串时,触发else规则,要求myObject必须为null,为对象会校验失败
完全匹配你列出的校验规则要求。
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

