JSON模式 - 如何使用oneOf

ksl*_*ksl 2 json jsonschema

以下是根据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" }
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

{
    "results" : {
        "result": "1"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jas*_*ers 13

看起来在这种情况下你想要的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"]
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,问题是如何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
            }
          ]
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Hur*_*rix 2

resultsobject是一种根据您架构定义的类型,但您提到类型为String。如果我将类型更改为object,它就可以正常工作。