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

JSON Schema如何实现数组首元素必填字段更少、其余元素全字段校验

问题解决方案

问题根源

你编写的JSON Schema本身完全符合JSON Schema Draft 2020-12规范,出现报错的核心原因是你使用的两款校验工具对Draft 2020-12的prefixItems特性支持存在缺陷:没有遵守「prefixItems仅校验数组前N个元素,items仅校验索引超出prefixItems长度的元素」的规则,错误地将items规则应用到了所有数组元素上。

解决方案

方案1:切换支持完整Draft 2020-12规范的校验实现

如果环境允许,优先选用对Draft 2020-12支持完整的校验库,你当前编写的Schema无需修改即可正常校验通过测试数据。

方案2:使用兼容旧草案的写法适配现有工具

如果必须使用当前的校验工具,可以将Schema调整为兼容Draft 07的写法,用数组形式的items定义首元素规则,additionalItems定义其余元素规则,修改后的完整Schema如下:

{
    "description": "Schema for array data",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "version": "0-0-6",
    "type": "object",
    "required": [
        "data"
    ],
    "properties": {
        "data": {
            "type": "array",
            "items": [{
                "type": "object",
                "required": [
                    "name"
                ],
                "properties": {
                    "name" : { "type" :"string" },
                    "age" : { "type" : "number" },
                    "city" : { "type" : "string" }  
                }
            }],
            "additionalItems": 
              {
                "type": "object",
                "required": [
                    "name", "age", "city"
                ],
                "properties": {
                    "name" : { "type" :"string" },
                    "age" : { "type" : "number" },
                    "city" : { "type" : "string" } 
                }
             }
        }
    }
}

该写法逻辑和你原有需求完全一致:数组第一个元素仅要求必填name,其余所有元素要求name、age、city三个字段全部必填,同时支持任意长度的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:54:04