根据“ type”属性验证JSON模式

时间:2019-11-25 23:35:39

标签: json validation jsonschema

我有以下JSON可以根据我当前的模式进行验证:

    {
      "information": [
        {
          "value": "closed",
          "type": "power"
        },
        {
          "value": "on",
          "type": "door"
        }
      ]
    }

但是,我希望此验证失败(因为open / closed应该与door相关,而on / off应该仅与{ {1}}。

我怎么把两者绑在一起?

我当前的工作模式:

power

我有很多类型,所以我想以最简洁的方式做到这一点。

这是我的尝试之一,无法正确验证:

  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "definitions": {
    "Type": {
      "type": "string",
      "enum": ["power", "door"]
    },
    "Power": {
      "type": "string",
      "enum": ["on", "off"]
    },
    "Door": {
      "type": "string",
      "enum": ["open", "closed"]
    },
    "InformationField": {
      "type": "object",
      "required": [ "type", "value" ],
      "properties": {
        "label": { "type": "string" },
        "value": {
          "anyOf": [
            { "$ref": "#/definitions/Power"},
            { "$ref": "#/definitions/Door"}
          ]
        },
        "type": { "$ref": "#/definitions/Type" }
      }
    },
    "Information": {
      "type": "array",
      "items": { "$ref": "#/definitions/InformationField" }
    },
  },
  "properties": {
    "information": { "$ref": "#/definitions/Information" }
  },
}

(进行验证,即使它不应该...)

1 个答案:

答案 0 :(得分:2)

我尝试将anyOf更改为allOf,以解决验证问题。

我对它为何起作用的理由:

根据anyOf JSON模式规范:

  

5.5.4.2。成功验证的条件

     

如果实例针对此关键字的值定义的至少一个架构成功验证,则实例针对此关键字成功验证。

如果我的第一个if条件为假,那么它不会评估then,因此有效

使用allOf评估每个条件的有效性(而不是条件本身)。