JSON Schema数组if-then-else校验异常:employee需必填batchId
解决JSON Schema中usertype关联user数组字段校验的问题
直接上修正后的JSON Schema,完全符合你要的校验逻辑:
{ "type": "object", "properties": { "usertype": { "type": "string", "enum": ["employee", "visitor"] }, "user": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "batchId": { "type": "string" } } } } }, "required": ["usertype", "user"], "if": { "properties": { "usertype": { "const": "employee" } } }, "then": { "properties": { "user": { "items": { "required": ["batchId"] } } } } }
关键修改点说明
- 用
if精准匹配usertype为"employee"的场景 - 在
then块中,专门对user数组的每一项(items)添加required: ["batchId"]规则,强制要求该字段存在 - 你之前的问题大概率是
if-then规则没作用到user.items这个层级,或者条件判断的范围没卡准
测试验证
拿你提到的「本该失败却通过」的测试数据举例:
{ "usertype": "employee", "user": [ { "name": "张三" } ] }
用上面的Schema校验时会直接报错,因为employee类型下的user对象缺少必填的batchId,符合预期。
如果是visitor类型,即使user数组里没有batchId也能正常通过:
{ "usertype": "visitor", "user": [ { "name": "李四" } ] }
内容的提问来源于stack exchange,提问作者wonuto
相关产品推荐
相关产品推荐

