我有一个像这样的json:
{"mylist": ["a", "b", "c", "d", last_element]}
这里,last_element 可以是以下四个字符串中的one:“w”、“x”、“y”、“z”;但不是多个。
示例:
{
"mylist": ["a", "b", "c", "d", "x"] // <-- valid
}
{
"mylist": ["b", "a", "y"] // <-- valid
}
{
"mylist": ["a", "b", "c", "d", "x", "y"] // <-- not valid
}
如何为此编写 jsonschema?
当前尝试:
{
"type":"object",
"properties":{
"mylist":{
"type":"array",
"items":{
"type":"string",
"enum":[
"a",
"b",
"c",
"d",
"w",
"x",
"y",
"z"
]
},
"minItems":1,
"uniqueItems":true
}
},
"required":[
"mylist"
],
"additionalProperties":false
}
您没有提到您正在使用哪个草稿版本,所以我给您举两个例子,它们的行为相似。
草案 04 - 2019 年 9 月
使用
items[]
定义每个索引的期望值的数组,并限制使用任何附加项
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"mylist": {
"type": "array",
"items": [
{
"$ref": "#/definitions/startOfArrayItems"
},
{
"$ref": "#/definitions/startOfArrayItems"
},
{
"$ref": "#/definitions/startOfArrayItems"
},
{
"$ref": "#/definitions/startOfArrayItems"
},
{
"enum": [
"w",
"x",
"y",
"z"
]
}
],
"minItems": 1,
"additionalItems": false,
"uniqueItems": true
}
},
"required": [
"mylist"
],
"additionalProperties": false,
"definitions": {
"startOfArrayItems": {
"enum": [
"a",
"b",
"c",
"d"
]
}
}
}
2020-12 草案
引入了新关键字
prefixItems
,其行为和语法与旧草案版本使用 items[]
相同。您可以使用 items: false
禁止数组中的其他项目
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"mylist": {
"type": "array",
"prefixItems": [
{
"$ref": "#/$defs/startOfArrayItems"
},
{
"$ref": "#/$defs/startOfArrayItems"
},
{
"$ref": "#/$defs/startOfArrayItems"
},
{
"$ref": "#/$defs/startOfArrayItems"
},
{
"enum": [
"w",
"x",
"y",
"z"
]
}
],
"minItems": 1,
"items": false,
"uniqueItems": true
}
},
"required": [
"mylist"
],
"additionalProperties": false,
"$defs": {
"startOfArrayItems": {
"enum": [
"a",
"b",
"c",
"d"
]
}
}
}