JSON模式-如何使用oneOf [英] JSON schema - how to use oneOf

查看:164
本文介绍了JSON模式-如何使用oneOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是根据 http://jsonlint.com/

根据上述架构进行验证时,以下JSON报告错误(results is the wrong type):

The following JSON reports an error (results is the wrong type) when validated against the above schema:

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

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

Can anyone suggest how I might resolve this error?

推荐答案

在这种情况下,您想要的是enum而不是oneOf.这是定义架构的方式.

It looks like what you want in this case is enum rather than oneOf. Here is how you would define your schema.

{
  "$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是字符串或整数.

But, the question was how to use oneOf properly. The oneOf keyword should be an array of schemas, not values as you have used in your example. One and only one of the schemas in oneOf must validate against the data for the oneOf clause to validate. I have to modify your example a little to illustrate how to use oneOf. This example allows result to be a string or an integer.

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

这篇关于JSON模式-如何使用oneOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆