JSON 架构:需要至少一个非位置数组元素
JSON Schema: require at least one non-positional array element
各位Whosebugers大家好!
我有一个 'problem',带有 JSON 模式代码并验证 JSON 数组。我的问题是我要求数组中至少有一个元素符合特定模式,但其余元素可以是自由形式的。我不能假设我搜索的元素位于数组的某个位置。仅使用整数(为简单起见)问题可以改写为:"write a schema that validates that there is at least one 1 in the array regardless of its position"。积极的例子是:
[1]
[0, 0, 1]
["a", true, null, 1, false, null, 3.2]
[1, 1, 1, 1]
负面例子是:
[]
["a"]
[0, 2, 4]
使用 json-schema.org (Draft 04) and playing around with the JSON Schema Validator 的文档,我想出了自己的解决方案,它使用双重否定,感觉很麻烦:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "testid",
"title": "test array schema",
"not": {
"items":
{
"not": { "enum": [1] }
}
}
}
使用了"not (for-all-items (not is 1))"的原理,虽然可以,但是感觉不是很优雅。我错过了数组的 "require" 之类的东西吗?
感谢反馈!
你没有遗漏任何东西。您可以为所有项指定一个架构,也可以为每个索引指定一个架构。这就是您需要处理的全部内容。
有人提议为 Draft 05 添加 contains
关键字,但 Draft 05 的进展现在已经停滞了一段时间。您拥有的架构是您可以使用 Draft 04 完成的最佳架构。
各位Whosebugers大家好!
我有一个 'problem',带有 JSON 模式代码并验证 JSON 数组。我的问题是我要求数组中至少有一个元素符合特定模式,但其余元素可以是自由形式的。我不能假设我搜索的元素位于数组的某个位置。仅使用整数(为简单起见)问题可以改写为:"write a schema that validates that there is at least one 1 in the array regardless of its position"。积极的例子是:
[1]
[0, 0, 1]
["a", true, null, 1, false, null, 3.2]
[1, 1, 1, 1]
负面例子是:
[]
["a"]
[0, 2, 4]
使用 json-schema.org (Draft 04) and playing around with the JSON Schema Validator 的文档,我想出了自己的解决方案,它使用双重否定,感觉很麻烦:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "testid",
"title": "test array schema",
"not": {
"items":
{
"not": { "enum": [1] }
}
}
}
使用了"not (for-all-items (not is 1))"的原理,虽然可以,但是感觉不是很优雅。我错过了数组的 "require" 之类的东西吗?
感谢反馈!
你没有遗漏任何东西。您可以为所有项指定一个架构,也可以为每个索引指定一个架构。这就是您需要处理的全部内容。
有人提议为 Draft 05 添加 contains
关键字,但 Draft 05 的进展现在已经停滞了一段时间。您拥有的架构是您可以使用 Draft 04 完成的最佳架构。