枚举列表作为json模式中的对象属性

时间:2019-05-17 15:21:44

标签: json jsonschema

我正在寻找一种方法来声明在枚举列表中定义的对象。

这是我要检查的内容:

{
  "object1": {
    "subobject1": {
      "value": 123
    },
    "subobject2": {
      "value": 456
    }
  },
  "object2": {
    "subobject3": {
      "value": 789
    }
  },
  "object3": {
    "subobject4": {
      "value": 123
    }
  },
  "object4": {
    "subobject5": {
      "value": 234
    }
  }
}

这是我要用于验证的架构:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "definitions": {
        "list1": {
            "enum": [
                "object1",
                "object2",
                "object3",
                "object4"
            ],
       "list2": {
            "enum": [
                "subobject1",
                "subobject2",
                "subobject3",
                "subobject4",
                "subobject5"
            ]
        }

        }
    },
    "properties": {
        "type": {
            "anyOf": [
                {
                    "$ref": "#/definitions/list1"
                }
            ]
        }
    },
    "additionalProperties": false
}

但是出现以下错误:

尚未定义属性'object1',并且该架构不允许其他属性。

我真的想非常严格,并且只能声明枚举中列出的那个,因为我知道如果删除“ additionalProperties”:false,我可以添加我想要的任何谱图,并且可以正常工作。

1 个答案:

答案 0 :(得分:0)

您给出的实例可以使用以下模式进行验证

{
    "type": "object",
    "definitions": {
      "list1": {
        "properties": {
          "subobject1": {"type": "object"},
          "subobject2": {"type": "object"},
          "subobject3": {"type": "object"},
          "subobject4": {"type": "object"},
          "subobject5": {"type": "object"}
        }
      }
   },
   "properties": {
     "object1": {"type": "object", "$ref": "#/definitions/list1"},
     "object2": {"type": "object", "$ref": "#/definitions/list1"},
     "object3": {"type": "object", "$ref": "#/definitions/list1"},
     "object4": {"type": "object", "$ref": "#/definitions/list1"}
   },
   "additionalProperties": false
}

也许这不是您想要的?我要关闭吗?