8

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?

ksl
  • 4,519
  • 11
  • 65
  • 106
  • works for me agains the validator http://s4.postimg.org/dysqmvn4t/Screen_Shot_2015_05_18_at_10_52_08.png – Samuel O May 18 '15 at 08:51
  • What I'm saying is that the JSON is valid but does not conform to the schema. Are you saying otherwise? – ksl May 18 '15 at 09:41

2 Answers2

26

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
            }
          ]
        }
      }
    }
  }
}
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
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.

  • This answer fixes the error that was reported, but the usage of `oneOf` is incorrect as well. With this change only, the value of `result` would not actually be constrained to 1-4. – Jason Desrosiers May 26 '15 at 18:25