我是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"}
}
}
我有以下架构来验证同一员工对象的数组:
{
"$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"}
}
}
}
您能否告诉我如何合并它们,以便我可以使用一个单一模式来验证单个员工对象或整个集合。感谢。
答案 0 :(得分:2)
(注意:此问题也在JSON Schema Google Group上提出,此答案也是从那里改编的。)
使用“$ref
”,您可以为您的数组添加类似的内容:
{
"type": "array",
"items": {"$ref": "/schemas/path/to/employee"}
}
如果您想要某个数组或单个项目,那么您可以使用“oneOf
”:
{
"oneOf": [
{"$ref": "/schemas/path/to/employee"}, // the root schema, defining the object
{
"type": "array", // the array schema.
"items": {"$ref": "/schemas/path/to/employee"}
}
]
}
原始Google网上论坛答案还包含一些使用"definitions"
组织模式的建议,因此所有这些变体都可以存在于同一个文件中。