【发布时间】:2019-04-18 22:49:17
【问题描述】:
我正在尝试验证比下面更复杂的 JSON,但希望这个更简单的示例清楚地说明了这个问题。
在更复杂的架构中,我需要一个对象数组,其中:
- 所有对象都有一组相同的属性,例如 Name 和 Type
- Type 属性是允许的对象类型的枚举,例如“全职”、“承包商”
- 根据 Type 属性的值,定义了额外的每个类型的属性集。例如,“全职”员工有一个必需的 Salary 属性和一个可选的 Email 属性,而“承包商”员工有一个 Rate 属性是必需的,没有可选的附加属性。
- 每个对象中只允许定义的属性
- 每个对象的必需属性可能包括所有对象共有的属性,例如 Name 和 Type,以及特定于一种对象类型的属性,例如作为薪水
这似乎应该是一个常见问题,但到目前为止,我还没有找到与我想要做的完全匹配的东西。这些接近了,但我无法确切地弄清楚如何将它们应用于和/或哪种方法最适合我的用例,因此希望更好地了解该领域的人可以提供帮助:
- Is it possible to have common properties before oneOf?
- How to validate a JSON object against a JSON schema based on object's type described by a field?
- how to set the type of a schema object based on the value of another property?
- JsonSchema: Validate type based on value of another property
具体来说,还不清楚 required 和 additionalProperties 关键字应该如何在通用属性和每个对象属性中起作用。
我目前的架构,有不必要的重复:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"$ref": "#/definitions/Employee"
},
"definitions": {
"Employee": {
"type": "object",
"oneOf": [{
"properties": {
"Name": { "type": "string" },
"Type": { "type": "string", "enum": [ "Full-Time" ] },
"Salary": { "type": "integer" },
"Email": { "type": "string" }
},
"required": [ "Name", "Type", "Salary" ],
"additionalProperties": false
},
{
"properties": {
"Name": { "type": "string" },
"Type": { "type": "string", "enum": [ "Contractor" ] },
"Rate": { "type": "number" }
},
"required": [ "Name", "Type", "Rate" ],
"additionalProperties": false
}]
}
}
}
验证这些数据:
[
{ "Name": "Good First Employee", "Type": "Full-Time", "Salary": 100000, "Email": "first.employee@example.com" },
{ "Name": "Good Second Employee", "Type": "Full-Time", "Salary": 90000 },
{ "Name": "Good First Contractor", "Type": "Contractor", "Rate": 20.00 },
{ "Name": "Good Second Contractor", "Type": "Contractor", "Rate": 25 },
{ "Name": "Bad First Person", "Type": "Unknown", "Salary": 90000 },
{ "Name": "Bad Third Employee", "Type": "Full-Time" },
{ "Name": "Bad Fourth Employee", "Type": "Full-Time", "Rate": 49.00 },
{ "Name": "Bad Fifth Employee", "Type": "Full-Time", "Salary": 100000, "Phone": "123-123-1234" },
{ "Name": "Bad Second Person" }
]
对于上述数据,名称以“Good”开头的对象是有效的。其余以“Bad”开头的无效:
- 第一人称错误 - 类型无效
- 糟糕的第三名员工 - 缺少薪水
- 错误的第四名员工 - 缺少薪水,员工的费率无效
- 错误的第五名员工 - 员工的电话无效
- 错误的第二人称 - 缺少类型(公共字段)
其中一些可行,但错误消息过多,无法清楚地指出问题所在。
【问题讨论】:
标签: json jsonschema