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

JSON Schema中数组内枚举验证失效问题排查

JSON Schema验证未生效的问题分析与修复

问题原因

你的JSON Schema中,items字段使用了数组形式(比如"items": [{...}]),这在JSON Schema draft-04中属于元组验证逻辑:

  • 数组的第1个元素会匹配items数组里的第1个schema规则
  • 数组中第2个及以后的元素,因为没有对应的items数组元素,不会被任何规则约束,默认通过验证

这就是为什么JSON里第2、3个ghrBillingCode不符合要求却能通过验证的核心原因。

修复方案

把items从数组形式改成单个对象,这样数组中的所有元素都会被统一的schema规则验证。修正后的Schema如下:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "invoiceLineInfo": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "ghrBillingCode": {
              "type": "string",
              "enum": ["I9NOT"]
            },
            "quantity": {
              "type": "integer"
            }
          },
          "required": ["ghrBillingCode", "quantity"] // 可选:强制字段必须存在
        }
      },
      "invoiceNumber": {
        "type": "string"
      }
    },
    "required": ["invoiceLineInfo", "invoiceNumber"] // 可选:强制顶层字段必须存在
  }
}

额外补充

如果需要确保ghrBillingCode和quantity是每个invoiceLineInfo元素的必填字段,可以加上required关键字(如上述代码注释部分),避免出现缺失字段的无效数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:27:15