JSON 模式中的多值枚举?
Multi-value enum in JSON schema?
我有一个包含字符串的数组,例如:
[ 'foo', 'bar' ]
可能的值是有限的。例如,有效值为 foo
、bar
和 baz
.
现在,当数组只包含有效值时,它应该是有效的,没有值超过一次,但它可以有任意数量的值。
有效数组的示例为 [ 'foo' ]
、[ 'foo', 'bar' ]
和 [ 'bar', 'baz' ]
。无效数组的示例为 []
、[ 'foo', 'foo' ]
和 [ 'bar', 'something-else' ]
.
如何使用 JSON 模式进行验证?到目前为止,我已经弄清楚了提供 minItems
和 uniqueItems
属性的 array
类型。我还想不通的是:How to allow multiple (but only valid) values? 我知道有 enum
,但这只允许一个值,不多个。
有人可以帮忙吗?
PS:以防万一,我使用 ajv 模块和 Node.js 到 运行 验证。
好吧,我自己搞定了……
您还需要提供 items
属性,然后为每个项目定义它需要 type: 'string'
并且它的值是 enum: [ 'foo', 'bar', 'baz' ]
.
这样你就可以确保每个单独的项目都是一个具有有效值的字符串,然后你对整个数组强制执行此操作☺️
更清楚地说明解决方案:
{
"type": "array",
"items": {
"type": "string",
"enum": [ "foo", "bar", "baz" ]
},
"uniqueItems": true,
"minItems": 1
}
参见:https://spacetelescope.github.io/understanding-json-schema/reference/array.html
我有一个包含字符串的数组,例如:
[ 'foo', 'bar' ]
可能的值是有限的。例如,有效值为 foo
、bar
和 baz
.
现在,当数组只包含有效值时,它应该是有效的,没有值超过一次,但它可以有任意数量的值。
有效数组的示例为 [ 'foo' ]
、[ 'foo', 'bar' ]
和 [ 'bar', 'baz' ]
。无效数组的示例为 []
、[ 'foo', 'foo' ]
和 [ 'bar', 'something-else' ]
.
如何使用 JSON 模式进行验证?到目前为止,我已经弄清楚了提供 minItems
和 uniqueItems
属性的 array
类型。我还想不通的是:How to allow multiple (but only valid) values? 我知道有 enum
,但这只允许一个值,不多个。
有人可以帮忙吗?
PS:以防万一,我使用 ajv 模块和 Node.js 到 运行 验证。
好吧,我自己搞定了……
您还需要提供 items
属性,然后为每个项目定义它需要 type: 'string'
并且它的值是 enum: [ 'foo', 'bar', 'baz' ]
.
这样你就可以确保每个单独的项目都是一个具有有效值的字符串,然后你对整个数组强制执行此操作☺️
更清楚地说明解决方案:
{
"type": "array",
"items": {
"type": "string",
"enum": [ "foo", "bar", "baz" ]
},
"uniqueItems": true,
"minItems": 1
}
参见:https://spacetelescope.github.io/understanding-json-schema/reference/array.html