【问题标题】:JSON Schema - only allow existing keys as value in another objectJSON Schema - 仅允许现有键作为另一个对象中的值
【发布时间】:2019-08-29 07:55:42
【问题描述】:

假设我有以下 JSON 对象:

{
    "firstKey": {
        "innerKey": null
    },
    "secondKey": {
        "innerKey": null
    },
    "thirdKey": {
        "innerKey": "firstKey"
    }
}

通过使用 JSON-Schema,我如何确保 innerKey 只能是 firstKeysecondKeynull(即如何只允许来自其他对象的现有键作为值) ?

【问题讨论】:

  • 这在当前版本的 JSON 模式下是不可能的。您需要检查一个单独的验证步骤。
  • 这可能不是您想要实现的,但是您可以定义一个枚举,因此 innerKey 只能是 ["firsKey", "secondKey", null] 之一。但是这个枚举应该通过指定键来构建。

标签: json jsonschema


【解决方案1】:

正如@Clemens 所说,这通常是不可能的。但是,如果您有带有 limited 数量的 well defined 属性的 JSON 输入,您可以尝试这样的操作。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "firstKey": {
      "properties": {
        "innerKey": {
          "allOf": [
            {
              "$ref": "#/definitions/innerKey"
            },
            {
              "not": {
                "const": "firstKey"
              }
            }
          ]
        }
      }
    },
    "secondKey": {
      "properties": {
        "innerKey": {
          "allOf": [
            {
              "$ref": "#/definitions/innerKey"
            },
            {
              "not": {
                "const": "secondKey"
              }
            }
          ]
        }
      }
    },
    "thirdKey": {
      "properties": {
        "innerKey": {
          "allOf": [
            {
              "$ref": "#/definitions/innerKey"
            },
            {
              "not": {
                "const": "thirdKey"
              }
            }
          ]
        }
      }
    }
  },
  "definitions": {
    "innerKey": {
      "oneOf": [
        {
          "enum": [
            "firstKey",
            "secondKey",
            "thirdKey"
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2020-12-26
    • 2019-12-24
    相关资源
    最近更新 更多