如何在JSON Schema中为数组首元素与其他元素设置不同required规则
JSON Schema 数组分位置校验调整方案
你可以通过JSON Schema的数组分位置校验能力实现需求,具体调整方式如下:
核心思路
JSON Schema 提供了针对数组前置元素的独立校验规则能力:
- 新版规范(Draft 2019-09及以后)使用
prefixItems定义数组前N个元素的各自校验规则 - 旧版规范(Draft 07及以前)使用数组形式的
items定义前置元素校验规则,搭配additionalItems定义剩余元素的校验规则 - 需要拆分两种元素的校验定义:首元素要求3个必填字段,其余元素要求2个必填字段
调整后完整Schema示例
{ "type": "object", "properties": { "Struct": { "type": "array", // 仅对第一个元素生效的校验规则 "prefixItems": [ { "$ref": "#/definitions/struct_first_element" } ], // 对第一个元素之后的所有元素生效的校验规则 "items": { "$ref": "#/definitions/struct_common_element" }, // 可选:限制数组最少有1个元素,按需开启 "minItems": 1 } }, "definitions": { "struct_first_element": { "type": "object", "required": ["Name", "Status", "Atouts"], "properties": { "Name": { "type": "string" }, "Status": { "type": "string" }, "Atouts": { "type": "array", "items": { "type": "object", "required": ["Name", "Value"], "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } } } } } }, "struct_common_element": { "type": "object", "required": ["Name", "Status"], "properties": { "Name": { "type": "string" }, "Status": { "type": "string" }, // 可选:如果允许后续元素额外携带Atouts字段则保留本行,不需要可删除 "Atouts": { "$ref": "#/definitions/struct_first_element/properties/Atouts" } } } } }
旧版规范兼容写法
如果你使用的是Draft 07及更早版本的Schema校验器,将Struct字段的校验替换为以下内容即可:
"Struct": { "type": "array", "items": [ { "$ref": "#/definitions/struct_first_element" } ], "additionalItems": { "$ref": "#/definitions/struct_common_element" }, "minItems": 1 }
补充说明
你提供的待校验JSON存在语法错误:数组末尾缺少闭合标识],实际使用时需要修正才能正常校验。
内容的提问来源于stack exchange,提问作者Didy7
相关产品推荐
相关产品推荐

