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

如何用JSON Schema验证数组含至少一个指定枚举值且非空?

如何在JSON Schema中要求数组非空且包含指定枚举值?

我需要用JSON Schema验证对象中的favoriteVegetables数组,要求该数组至少包含carrot、lettuce、cucumber中的一个值(可包含任意或全部枚举值),但不能是空数组。

当前使用的Schema如下:

{
  "$id": "https://www.example.com/vegetables.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Vegetables",
  "required": [ "favoriteVegetables" ],
  "type": "object",
  "properties": {
    "favoriteVegetables": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": ["carrot", "lettuce", "cucumber"]
      }
    },
  },
  "additionalProperties": false
}

现在的问题是这个Schema会允许favoriteVegetables为空数组[],请问该如何修改以添加“数组必须至少有一个元素”的验证规则?


只需在favoriteVegetables的数组配置中添加"minItems": 1即可。minItems是JSON Schema中专门用于限制数组最小元素数量的关键字,设置为1就能直接禁止空数组通过验证。结合原有的items枚举规则,就能同时满足“元素必须是指定蔬菜”和“数组非空”的要求。

修改后的完整Schema如下:

{
  "$id": "https://www.example.com/vegetables.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Vegetables",
  "required": [ "favoriteVegetables" ],
  "type": "object",
  "properties": {
    "favoriteVegetables": {
      "type": "array",
      "minItems": 1,
      "items": {
        "type": "string",
        "enum": ["carrot", "lettuce", "cucumber"]
      }
    }
  },
  "additionalProperties": false
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:48:35