我是 JSON 和 JSON 模式验证的新手。
我有以下模式来验证单个员工对象:
{
"$schema":"http://json-schema.org/draft-03/schema#",
"title":"Employee Type Schema",
"type":"object",
"properties":
{
"EmployeeID": {"type": "integer","minimum": 101,"maximum": 901,"required":true},
"FirstName": {"type": "string","required":true},
"LastName": {"type": "string","required":true},
"JobTitle": {"type": "string"},
"PhoneNumber": {"type": "string","required":true},
"Email": {"type": "string","required":true},
"Address":
{
"type": "object",
"properties":
{
"AddressLine": {"type": "string","required":true},
"City": {"type": "string","required":true},
"PostalCode": {"type": "string","required":true},
"StateProvinceName": {"type": "string","required":true}
}
},
"CountryRegionName": {"type": "string"}
}
}
Run Code Online (Sandbox Code Playgroud)
我有以下模式来验证同一员工对象的数组:
{
"$schema": "http://json-schema.org/draft-03/schema#",
"title": "Employee set",
"type": "array",
"items":
{
"type": "object",
"properties":
{
"EmployeeID": {"type": "integer","minimum": 101,"maximum": 301,"required":true},
"FirstName": {"type": "string","required":true},
"LastName": {"type": "string","required":true},
"JobTitle": {"type": "string"},
"PhoneNumber": {"type": "string","required":true},
"Email": {"type": "string","required":true},
"Address":
{
"type": "object",
"properties":
{
"AddressLine": {"type": "string","required":true},
"City": {"type": "string","required":true},
"PostalCode": {"type": "string","required":true},
"StateProvinceName": {"type": "string","required":true}
}
},
"CountryRegionName": {"type": "string"}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我如何合并它们,这样我就可以使用一个单一的模式来验证单个员工对象或整个集合。谢谢。
(注意:这个问题也在JSON Schema Google Group上被问到,这个答案是从那里改编的。)
使用“ $ref”,你的数组可以有这样的东西:
{
"type": "array",
"items": {"$ref": "/schemas/path/to/employee"}
}
Run Code Online (Sandbox Code Playgroud)
如果你想要一个数组或单个项目,那么你可以使用“ oneOf”:
{
"oneOf": [
{"$ref": "/schemas/path/to/employee"}, // the root schema, defining the object
{
"type": "array", // the array schema.
"items": {"$ref": "/schemas/path/to/employee"}
}
]
}
Run Code Online (Sandbox Code Playgroud)
原始的 Google 网上论坛答案还包含一些有关使用"definitions"组织架构的建议,以便所有这些变体都可以存在于同一文件中。