JSON Schema 嵌套对象定义指南
嵌套对象就是把 properties 一层层写进去。关键点是「每一层对象都有自己的 type/properties/required」。
两层嵌套
{
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"name": { "type": "string" },
"address": {
"type": "object",
"properties": {
"city": { "type": "string" },
"zip": { "type": "string" }
},
"required": ["city", "zip"]
}
},
"required": ["name", "address"]
}
},
"required": ["user"]
}
对应 JSON:
{
"user": {
"name": "Ada",
"address": { "city": "London", "zip": "EC1" }
}
}
数组里的对象嵌套
当数组元素是对象时,items 里再放一层 properties。如果数组里每个对象的字段不完全一致,工具会把多个对象出现过的 key 合并,未在所有对象里出现的字段不计入 required。
小技巧
- 嵌套越深,越容易漏
required,建议用工具生成后逐层核对。 - 可选子对象(有时缺
address)就不要放进required。