JSON模式oneOf验证

时间:2018-07-09 17:44:10

标签: json jsonschema json-schema-validator

我正在尝试创建一个JSON模式,该属性将允许属性为数字或特定格式的对象。

我的数据如下:

{
  "num": 200
}

我的模式如下:

{
  "properties": {
    "num": {
      "type": [
        "number",
        "object"
      ],
      "oneOf": [
        {
          "type": "number"
        },
        {
          "$ref": "#/definitions/Variable"
        }
      ]
    }
  },
  "required": [
    "num"
  ],
  "additionalProperties": false,
  "definitions": {
    "Variable": {
      "title": "Variable",
      "properties": {
        "$variable$": {
          "type": "boolean",
          "example": true
        },
        "name": {
          "type": "string"
        },
        "defaultValue": {
          "type": [
            "string",
            "object",
            "number"
          ]
        }
      },
      "required": [
        "$variable$",
        "name"
      ],
      "additionalProperties": false
    }
  }
}

当我在此处通过验证程序运行它时:https://www.jsonschemavalidator.net/

我收到此错误:

Message: JSON is valid against more than one schema from 'oneOf'. Valid schema indexes: 0, 1.
Schema path: #/properties/num/oneOf

我假设我对oneOf的工作方式缺少明显的了解,但我不知道该怎么办。希望在这里提供任何帮助,谢谢!

2 个答案:

答案 0 :(得分:3)

您遇到的错误是告诉您您两个oneOf模式都已验证为true。值4在以下模式下有效可能令人惊讶。

{
  "properties": {
    "foo": { "type": "string": }
  },
  "required": ["foo"]
}

事实证明,当值不是对象时,properties关键字和required关键字不适用。因此,当根据数字(或不是对象的任何东西)进行验证时,上述模式实际上是空模式({})。因为空模式意味着没有约束,所以一切都是有效的。

要解决您的问题,只需将"type": "object"添加到您的/definitions/Variable模式中。

答案 1 :(得分:-1)

对于您的情况,您根本不需要oneOf,只需使用 “ type”:[“ number”,{“ $ ref”:“#/ definitions / Variable”}]而不是“ type”:[“ number”,“ object”]

{
  "properties": {
    "num": {
      "type": [
        "number",{"$ref":"#/definitions/Variable"}
      ]
    }
  },
  "required": [
    "num"
  ],
  "additionalProperties": false,
  "definitions": {
    "Variable": {
      "title": "Variable",
      "properties": {
        "$variable$": {
          "type": "boolean",
          "example": true
        },
        "name": {
          "type": "string"
        },
        "defaultValue": {
          "type": [
            "string",
            "object",
            "number"
          ]
        }
      },
      "required": [
        "$variable$",
        "name"
      ],
      "additionalProperties": false
    }
  }
}