You need to enable JavaScript to run this app. 如何调整JSON Schema Draft-07使groups空数组与含元素数组均通过校验
优惠活动
大模型
产品
解决方案
定价
更多

如何调整JSON Schema Draft-07使groups空数组与含元素数组均通过校验

问题根源

原Schema中groups字段的items规则使用了仅包含单分支的anyOf包裹,该写法属于冗余设计:anyOf的作用是提供多套可选校验规则,仅存在一个分支时和直接编写该规则没有区别。部分Draft-07版本的校验器实现对此类场景存在兼容问题,会误判空数组必须至少有一个元素满足anyOf规则,导致groups: []的返回结果被判定为非法。

调整方案

去掉冗余的anyOf包裹,直接将单分支的对象校验规则作为groups的items校验规则即可。调整后的完整Schema如下:

var schema = {
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "http://example.com/example.json",
  "type": "object",
  "required": [
    "data"
  ],
  "properties": {
    "data": {
      "$id": "#/properties/data",
      "type": "object",
      "required": [
        "id",
        "name",
        "description",
        "groups"
      ],
      "properties": {
        "id": {
          "$id": "#/properties/data/properties/id",
          "type": "integer"
        },
        "name": {
          "$id": "#/properties/data/properties/name",
          "type": "string"
        },
        "description": {
          "$id": "#/properties/data/properties/description",
          "type": "string"
        },
        "groups": {
          "$id": "#/properties/data/properties/groups",
          "type": "array",
          "items": {
            "$id": "#/properties/data/properties/groups/items",
            "type": "object",
            "required": [
              "id",
              "name",
              "description"
            ],
            "properties": {
              "id": {
                "$id": "#/properties/data/properties/groups/items/properties/id",
                "type": "integer"
              },
              "name": {
                "$id": "#/properties/data/properties/groups/items/properties/name",
                "type": "string"
              },
              "description": {
                "$id": "#/properties/data/properties/groups/items/properties/description",
                "type": "string"
              }
            }
          }
        }
      }
    }
  }
};

调整后items的校验逻辑为「数组内每个元素必须符合指定对象结构」,空数组无元素需要校验,自然满足规则;带元素的数组只要元素符合对象结构即可通过,完全匹配两类返回结果的校验需求。
如果仍遇到校验器兼容问题,可以额外给groups字段补充显式声明"minItems": 0(该值为JSON Schema默认值,显式声明可规避部分校验器的默认值处理偏差)。


内容的提问来源于stack exchange,提问作者A. Gladkiy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 01:15:03