繁体   English   中英

JSON模式 - 如何使用oneOf

[英]JSON schema - how to use oneOf

以下是根据http://jsonlint.com/http://jsonschemalint.com/draft4/#的有效JSON架构。

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": ["results"],
    "additionalProperties": false,
    "properties": {
        "results": {
            "type": "string",
            "oneOf": [
                { "result": "1" },
                { "result": "2" },
                { "result": "3" },
                { "result": "4" }
            ]
        }
    }
}

在针对上述模式进行验证时,以下JSON报告错误( results is the wrong type ):

{
    "results" : {
        "result": "1"
    }
}

任何人都可以建议我如何解决此错误?

看起来在这种情况下你想要的是enum而不是oneOf 以下是定义架构的方法。

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["results"],
  "additionalProperties": false,
  "properties": {
    "results": {
      "type": "object",
      "properties": {
        "result": {
          "type": "string",
          "enum": ["1", "2", "3", "4"]
        }
      }
    }
  }
}

但是,问题是如何正确使用oneOf oneOf关键字应该是一个模式数组,而不是您在示例中使用的值。 oneOf只有一个模式必须验证oneOf子句要验证的数据。 我必须稍微修改你的例子来说明如何使用oneOf 此示例允许result为字符串或整数。

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["results"],
  "additionalProperties": false,
  "properties": {
    "results": {
      "type": "object",
      "properties": {
        "result": {
          "oneOf": [
            {
              "type": "string",
              "enum": ["1", "2", "3", "4"]
            },
            {
              "type": "integer",
              "minimum": 1,
              "maximum": 4
            }
          ]
        }
      }
    }
  }
}

results是根据您的模式定义的一种object ,但您提到类型为String 如果我将类型更改为object ,它只是工作正常。

暂无
暂无

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

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