You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:10:00