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

JSON Schema验证:all_fruit不能与其他水果共存的数组校验

正确的JSON Schema验证方案

核心思路

用oneOf关键字划分两种互斥的合法场景,直接规避if-then逻辑容易出现的边界误判问题。两种合法情况明确为:

  1. 数组仅包含"all_fruit"一个元素
  2. 数组包含任意数量(至少1个)的非"all_fruit"水果,且完全不包含"all_fruit"

第一步:定义水果枚举Schema

{
  "$id": "FruitEnum",
  "type": "string",
  "enum": ["apple", "banana", "orange", "all_fruit"]
}

第二步:定义水果篮验证Schema

通过oneOf组合两个互斥的验证规则:

{
  "$id": "FruitBasket",
  "type": "object",
  "properties": {
    "fruits": {
      "oneOf": [
        // 场景1:仅包含"all_fruit"
        {
          "type": "array",
          "items": {"$ref": "FruitEnum"},
          "minItems": 1,
          "maxItems": 1,
          "contains": {"const": "all_fruit"}
        },
        // 场景2:仅包含非"all_fruit"的水果
        {
          "type": "array",
          "items": {
            "$ref": "FruitEnum",
            "not": {"const": "all_fruit"}
          },
          "minItems": 1,
          "not": {"contains": {"const": "all_fruit"}}
        }
      ]
    }
  },
  "required": ["fruits"]
}

规则说明

  1. 场景1:通过maxItems:1+contains:"all_fruit",严格限制数组只能有"all_fruit"这一个元素,杜绝重复或混合其他水果的情况。
  2. 场景2:
    • items.not确保每个元素都不是"all_fruit"
    • not.contains确保整个数组里完全没有"all_fruit"
    • minItems:1避免空数组的非法情况
  3. oneOf:保证两种场景只能满足其一,天然实现"要么选子集,要么选all"的互斥要求。

测试用例示例

  • ✅ 合法:{"fruits": ["all_fruit"]}
  • ✅ 合法:{"fruits": ["apple", "orange"]}
  • ❌ 非法:{"fruits": ["all_fruit", "banana"]}(同时包含all和其他水果)
  • ❌ 非法:{"fruits": ["all_fruit", "all_fruit"]}(重复all元素)
  • ❌ 非法:{"fruits": []}(空数组)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:30:55