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

如何用JSON Schema确保参与者数组仅含一名候选人和多名面试官

修正后的JSON Schema方案

核心思路

通过allOf组合两组校验规则,精准满足你的需求:

  1. 强制数组恰好包含1个符合候选人Schema的元素;
  2. 强制数组中所有元素要么是候选人,要么是面试官,杜绝非法对象混入。

具体实现代码

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "allOf": [
    // 规则1:确保恰好1名候选人
    {
      "contains": {
        "type": "object",
        "required": ["name", "email"], // 替换为候选人实际必填字段
        "properties": {
          "name": { "type": "string" },
          "email": { "type": "string", "format": "email" }
        },
        "not": { "required": ["certification"] }, // 明确排除面试官专属字段
        "additionalProperties": false // 若候选人只能有指定字段则保留,否则删除
      },
      "minContains": 1,
      "maxContains": 1
    },
    // 规则2:所有元素必须是候选人或面试官
    {
      "items": {
        "anyOf": [
          // 复用候选人Schema
          {
            "type": "object",
            "required": ["name", "email"],
            "properties": {
              "name": { "type": "string" },
              "email": { "type": "string", "format": "email" }
            },
            "not": { "required": ["certification"] }
          },
          // 面试官Schema
          {
            "type": "object",
            "required": ["name", "email", "certification"],
            "properties": {
              "name": { "type": "string" },
              "email": { "type": "string", "format": "email" },
              "certification": { "type": "string" } // 可根据需求调整类型,比如枚举值
            }
          }
        ]
      }
    }
  ]
}

关键校验点说明

  • contains + minContains/maxContains:精准锁定候选人数量为1,解决原anyOf无法控量的问题;
  • not: {required: ["certification"]}:确保候选人绝对不会出现面试官特有的字段;
  • items.anyOf:约束数组所有元素只能是两种合法类型,避免出现无效对象;
  • 可根据实际业务调整required和properties,比如给面试官的certification添加枚举限制。

验证场景覆盖

  • ✅ 1名候选人 + N名面试官:校验通过;
  • ❌ 无候选人:minContains触发失败;
  • ❌ 超过1名候选人:maxContains触发失败;
  • ❌ 候选人带certification字段:not规则触发失败;
  • ❌ 面试官缺certification字段:面试官Schema的required触发失败;
  • ❌ 出现非法对象:items.anyOf触发失败。

内容的提问来源于stack exchange,提问作者Cheeter_P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:25:23