【问题标题】:Validating nested list of numbers/booleans with JSON schema使用 JSON 模式验证数字/布尔值的嵌套列表
【发布时间】:2017-06-19 22:22:05
【问题描述】:

我不确定 JSON 模式是否可行,但我有类似的数据:

[1, 1, [0, 0, [true]], true]

如何验证 [0, 0, 1] 以使其中至少一项为 1/true?

到目前为止,我已经设法创建了架构:

{
  "type": "array",
  "items": {
    "$ref": "#/definitions/_items"
  },
  "definitions": {
    "_items": {
      "anyOf": [
        {
          "enum": [
            0,
            1
          ],
          "type": "integer"
        },
        {
          "enum": [
            false,
            true
          ],
          "type": "boolean"
        },
        {
          "type": "array",
          "items": {
            "anyOf": [
              {
                "$ref": "#/definitions/_items"
              }
            ]
          }
        }
      ]
    }
  }
}

显然,它确实验证了所有接受的值,但它没有考虑是否存在所有、一些、一个或没有值 1 / true。我误解了,anyOf、allOf 和 oneOf 是为此保留的……

【问题讨论】:

    标签: json validation nested jsonschema


    【解决方案1】:

    您需要的是contains 关键字。这计划在下一版本的 JSON Schema 规范中添加。在实现之前,不用contains也可以,但是逻辑有点复杂。到目前为止,我还清理了一些不必要的部分。

    {
      "type": "array",
      "items": { "$ref": "#/definitions/_items" },
      "allOf": [{ "$ref": "#/definitions/contains-1-or-true" }],
      "definitions": {
        "_items": {
          "anyOf": [
            { "enum": [0, 1] },
            { "type": "boolean" },
            { "$ref": "#" }
          ]
        },
        "contains-1-or-true": {
          "not": {
            "type": "array",
            "items": {
              "not": { "enum": [1, true] }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 我最终得到了非常相似的解决方案,使用 not not 表示法。你能解释一下为什么这里需要 anyOf ref # 吗?这真的对深度嵌套结构递归有效吗?
    • 是的,这适用于任何级别的嵌套。 { "$ref": "#" } 指的是整个模式。这是一个递归引用。或者,您可以通过复制前三行来做到这一点(类似于您所拥有的)。但是,递归引用是一种更简洁的解决方案,因为它消除了重复。
    • 我打开了其他与此非常相关的问题,您@Jason 可能能够给出答案:stackoverflow.com/questions/42026162/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 2015-06-17
    相关资源
    最近更新 更多