是否可以强制定义已知对象(“敌人”和“朋友”)而允许其他对象?
我添加了最后一个对象 {"type": "object"} 来显示预期的行为 - 但实际上最后一个对象将推翻两个定义的对象(“enemy”和“friend”),导致任何类型的对象对此模式有效。如果我删除最后一个对象,它将允许这两个对象,但没有别的。
JSON 模式(使用数组进行更快的测试):
{
"type": "array",
"items": {
"anyOf": [
{"$ref": "#/definitions/friend"},
{"$ref": "#/definitions/enemy"},
{"$ref": "#/definitions/future"}
]
},
"definitions": {
"friend": {
"type": "object",
"properties": {
"time": {"type": "string"},
"value": {"type": "number", "minimum": 100}
},
"required": ["time", "value"],
"additionalProperties": false
},
"enemy": {
"type": "object",
"properties": {
"enemy": {"type": "string"},
"color": {"type": "number"}
},
"required": ["enemy", "color"],
"additionalProperties": false
},
"future": {
"type": "object",
"properties": {
"time": {"type": "string"}
}, "required": ["time"],
"additionalProperties": true
}
}
}
JSON 示例(前 3 个应该没问题,后 3 个应该没问题):
[
{"time": "123", "value": 100}, <- should be valid
{"time": "1212", "value": 150}, <- should be valid
{"enemy": "bla", "color": 123}, <- should be valid
{"time": "1212", "value": 50}, <- should be invalid bcoz of "future"
{"enemy": "bla", "color": "123"}, <- shouldn't be valid bcoz of "enemy" schema
{"somethingInFuture": 123, "someFutProp": "ok"} <- should be valid
]