JSON模式中的多值枚举?

时间:2021-01-29 08:22:18

I have an array that contains strings, such as:

我有一个包含字符串的数组,例如:

[ 'foo', 'bar' ]

The possible values are limited. For example, valid values are foo, bar, and baz.

可能的价值是有限的。例如,有效值是foo、bar和baz。

Now the array shall be valid when it contains only values that are valid, no value more than once, but it can have an arbitrary number of values.

现在数组应该是有效的,当它只包含有效的值,值不超过一次,但是它可以有任意数量的值。

Examples for valid arrays would be [ 'foo' ], [ 'foo', 'bar' ], and [ 'bar', 'baz' ]. Examples for invalid arrays would be [], [ 'foo', 'foo' ], and [ 'bar', 'something-else' ].

有效数组的示例有['foo']、['foo'、'bar'和['bar'、'baz']。无效数组的例子有[]、['foo'、'foo']和['bar'、'something else']。

How can I do this validation using JSON schema? So far, I have figured out the array type which provides the minItems and the uniqueItems properties. What I could not yet figure out is: How to allow multiple (but only valid) values? I know that there is enum, but this only allows a single value, not multiple ones.

如何使用JSON模式进行验证?到目前为止,我已经计算出提供minItems和uniqueItems属性的数组类型。我还不能确定的是:如何允许多个(但只有有效的)值?我知道有enum,但这只允许一个值,而不是多个值。

Can anybody help?

有人能帮忙吗?

PS: Just in case it matters, I'm using the ajv module with Node.js to run the validation.

PS:以防万一,我用的是带节点的ajv模块。运行验证。

2 个解决方案

#1


1  

Spelling out the solution more clearly:

更清楚地阐明解决方案:

{
  "type": "array",
  "items": {
    "type": "string",
    "enum": [ "foo", "bar", "baz" ]
  },
  "uniqueItems": true,
  "minItems": 1
}

See: https://spacetelescope.github.io/understanding-json-schema/reference/array.html

参见:https://spacetelescope.github.io/understanding-json-schema/reference/array.html

#2


0  

Okay, I got it by myself…

好吧,我自己弄的……

You need to provide the items property as well, and then for each item define that it needs to be of type: 'string' and its value to be an enum: [ 'foo', 'bar', 'baz' ].

您还需要提供items属性,然后为每个项定义它需要类型为:'string',其值为enum: ['foo'、'bar'、'baz']。

This way you ensure that each single items is a string with a valid value, and then you enforce this for the entire array ☺️

这种方式可以确保每一个项目是一个字符串和一个有效的值,然后执行这个整个数组☺️

#1


1  

Spelling out the solution more clearly:

更清楚地阐明解决方案:

{
  "type": "array",
  "items": {
    "type": "string",
    "enum": [ "foo", "bar", "baz" ]
  },
  "uniqueItems": true,
  "minItems": 1
}

See: https://spacetelescope.github.io/understanding-json-schema/reference/array.html

参见:https://spacetelescope.github.io/understanding-json-schema/reference/array.html

#2


0  

Okay, I got it by myself…

好吧,我自己弄的……

You need to provide the items property as well, and then for each item define that it needs to be of type: 'string' and its value to be an enum: [ 'foo', 'bar', 'baz' ].

您还需要提供items属性,然后为每个项定义它需要类型为:'string',其值为enum: ['foo'、'bar'、'baz']。

This way you ensure that each single items is a string with a valid value, and then you enforce this for the entire array ☺️

这种方式可以确保每一个项目是一个字符串和一个有效的值,然后执行这个整个数组☺️