首页 > 解决方案 > JSON Schema oneOf 验证

问题描述

我正在尝试创建一个 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工作的明显内容,但我无法弄清楚它可能是什么。在此不胜感激,谢谢!

标签: jsonjsonschemajson-schema-validator

解决方案


你得到的错误是告诉你你们两个oneOf模式都验证为真。令人惊讶的是,该值4对以下模式有效。

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

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

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


推荐阅读