JSON schema - how to use oneOf

2019-08-03 06:48发布

问题:

The following is a valid JSON schema according to http://jsonlint.com/ and http://jsonschemalint.com/draft4/#.

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

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?

回答1:

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

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
            }
          ]
        }
      }
    }
  }
}


回答2:

results is a type of object as per you schema definition but you mentioned type as String. If I change the type as object, It just works fine.