繁体   English   中英

JSON模式oneOf验证

[英]JSON Schema oneOf validation

我正在尝试创建一个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工作原理的明显信息,但是我无法弄清楚它可能是什么。 希望在这里提供任何帮助,谢谢!

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM