JSON模式-仅允许将现有键作为另一个对象中的值

时间:2019-08-29 07:55:42

标签: json jsonschema

假设我有以下JSON对象:

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

通过使用JSON-Schema,如何确定innerKey只能是firstKeysecondKeynull(即,如何只允许现有密钥来自另一个对象作为值)?

1 个答案:

答案 0 :(得分:0)

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

{
  "$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"
        }
      ]
    }
  }
}