如何针对包含多层引用的复杂JSON Schema验证JSON数据
问题根源
你在定义cropLocation字段的校验规则时混用了数组和对象类型的校验关键字:
items是数组类型专用的校验关键字,仅当字段的type为array时才会生效- 你将
cropLocation声明为type: object,JSON Schema会直接忽略对object类型不生效的items配置,因此你关联的#/$defs/location规则完全没有生效,只要cropLocation是对象就能通过校验。
修正方案
直接将cropLocation的校验规则指向你定义好的location结构即可,修正后的完整Schema如下:
{ "$id": "https://example.com/arrays.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "A representation of a person, company, organization, or place", "type": "object", "properties": { "fruits": { "type": "array", "items": { "type": "string" } }, "vegetables": { "type": "array", "items": { "$ref": "#/$defs/veggie" } } }, "required" : ["fruits", "vegetables"], "$defs": { "veggie": { "type": "object", "required": [ "veggieName", "veggieLike", "cropLocation"], "properties": { "veggieName": { "type": "string" }, "veggieLike": { "type": "boolean" }, "cropLocation": { "$ref" : "#/$defs/location" } } }, "location" : { "type" : "object", "required" : ["country", "state"], "properties" : { "country" : { "type": "string" }, "state" : { "type": "string" } } } } }
校验效果
用你提供的测试数据校验时,会准确抛出如下错误:
- 第1个vegetable的cropLocation缺少必填字段
country、state - 第2个vegetable的cropLocation缺少必填字段
country、state
完全符合预期校验逻辑。
多层复杂对象定义注意事项
定义嵌套结构时注意对应类型的关键字不要混用:
- 数组类型使用
items指定数组元素的校验规则 - 对象类型直接在
properties里配置对应字段的校验规则,或者通过$ref引用提前定义好的公共结构 - 嵌套层级没有限制,只要每一层的类型和对应校验关键字匹配即可生效。
内容的提问来源于stack exchange,提问作者Karthik G
相关产品推荐
相关产品推荐

