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

如何使用JSON Schema检查字符串数组的元素数量是否为奇数?

能否用JSON Schema检查字符串数组的元素数量是否为奇数?

可以实现,不过需要依赖JSON Schema Draft 7及以上版本支持的$expr关键字(主流验证器如AJV均支持该特性),也可以通过组合关键字的方式兼容部分旧版本。以下是两种可行方案:

方案一:使用$expr表达式校验(推荐)

利用$expr编写表达式判断数组长度对2取余不等于0,同时确保数组元素均为字符串:

{
  "type": "object",
  "properties": {
    "list": {
      "type": "array",
      "items": { "type": "string" },
      "$expr": {
        "$ne": [ { "$mod": [ { "$size": "list" }, 2 ] }, 0 ]
      }
    }
  },
  "required": ["list"]
}

方案二:组合关键字实现(兼容旧版本)

通过contains和not组合间接判断数组长度为奇数,该方案仅适用于数组元素非空的场景:

{
  "type": "object",
  "properties": {
    "list": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 1,
      "not": {
        "contains": {},
        "contains": {}
      }
    }
  },
  "required": ["list"]
}

验证示例

有效示例1

{
  "list": [
    "one",
    "two",
    "three"
  ]
}

有效示例2

{
  "list": [
    "one",
    "two",
    "three",
    "four",
    "five"
  ]
}

无效示例

{
  "list": [
    "one",
    "two",
    "three",
    "four"
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:32:05