JSON Schema数组特定类型校验失效问题排查求助
JSON Schema校验失效问题排查与修复
核心问题分析
你的Schema存在两处语法错误,直接导致校验约束完全失效:
1. 对象属性定义未使用properties关键字包裹
在trainzMeshes.items.anyOf的第一个分支、blenderExportSpecifications.items.anyOf的第二个分支中,你直接将comment字段写在Schema顶层,而非嵌套在properties中。JSON Schema会将非标准关键字(如直接写的comment)视为自定义关键字并忽略,这使得这两个分支变成无约束的空Schema,可以匹配任何值。
错误示例:
{ "comment": { "$ref": "#/$defs/comment" }, "minItems": 0 }
2. 误用数组关键字在对象Schema中
你在对象类型的Schema分支中使用了minItems、minContains这类仅适用于数组的关键字,这些关键字在对象Schema中会被校验器直接忽略,进一步削弱了约束能力。
修复后的关键Schema片段
修复trainzMeshes的items约束
"trainzMeshes": { "title": "Trainz Meshes", "description": "Specifications of Trainz meshes to create as FBX files and comments specified as an array.", "type": "array", "additionalItems": false, "items": { "anyOf": [ { "type": "object", "additionalProperties": false, "properties": { "comment": { "$ref": "#/$defs/comment" } }, "required": ["comment"] }, { "$ref": "#/$defs/trainzMesh" } ] } }
修复blenderExportSpecifications的items约束
"blenderExportSpecifications": { "title": "Blender Export Specifications", "description": "Specifies one or more Blender objects, with optionally assigning a material and UV map to each, to include them in the Trainz mesh FBX file.", "type": "array", "minItems": 1, "additionalItems": false, "items": { "anyOf": [ { "$ref": "#/$defs/blenderExportSpecification" }, { "type": "object", "additionalProperties": false, "properties": { "comment": { "$ref": "#/$defs/comment" } }, "required": ["comment"] } ] } }
修复效果验证
修复后,测试JSON中的includeObject字段会触发预期的校验失败:
- 该对象不符合
blenderExportSpecification的约束(无合法属性,additionalProperties: false触发违规); - 该对象也不符合评论对象的要求(无
comment属性),因此anyOf分支全部不匹配,数组元素校验失败。
内容的提问来源于stack exchange,提问作者T1nk-R
相关产品推荐
相关产品推荐

