具有数组属性的多组枚举的JSON架构定义



我想为一个对象创建一个JSON模式,其中一个属性被限制为多组枚举。

例如:

{
"data": {
"type": "myObject",
"attributes": {
"states": [
"Washington",
"Oregon",
"California"
]
}
}
}

是针对架构的有效JSON对象。和

{
"data": {
"type": "myObject",
"attributes": {
"states": [
"British Columbia",
"Alberta",
"Ontario"
]
}
}
}

也是模式中的有效JSON对象

但是,

{
"data": {
"type": "myObject",
"attributes": {
"states": [
"Washington",
"Oregon",
"Alberta"
]
}
}
}

不是针对架构的有效JSON对象。

我尝试了以下模式定义:

{
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"attributes": {
"type": "object",
"properties": {
"states": {
"type": "array",
"items": {
"oneOf": [
{
"enum": ["Washington","Oregon","California"],
"description": "United States"
},
{
"enum": ["British Columbia","Alberta", "Ontario"],
"description": "Canada"
}
]
},
"description": "Filter by states"
}
}
}
}
}
}
}

但对于上面的这个模式,这仍然被认为是有效的:

{
"data": {
"type": "myObject",
"attributes": {
"states": [
"Washington",
"Oregon",
"Alberta"
]
}
}
}

顺便说一句,您可以使用它来测试JSON对象是否符合模式:https://www.jsonschemavalidator.net/

谢谢!

您需要反转oneOf和items关键字的顺序,以便对所有项使用相同的oneOf子句:

...
"states": {
"type": "array",
"oneOf": [
{
"items": {
"enum": ["Washington","Oregon","California"],
"description": "United States"
}
},
{
"items": {
"enum": ["British Columbia","Alberta", "Ontario"],
"description": "Canada"
}
}
]
},
...

最新更新