Search code examples
conditional-statementsjsonschemaany

JSON Schema - anyOf within conditional?


I am trying to define a JSON schema with conditionals. I built an MVE which already doesn't work as I expect it.

The object I want to validate is:

{
  "keiner": false, 
  "abdominal": true,
  "zervikal": false
}

The conditional rule is simple. When "keiner" is true, both other values have to be false. If "keiner" is false, at least one of the other two has to be true.

I wrote this schema:

{
  "type": "object",
  "properties": {
    "keiner": { "type": "boolean" },
    "abdominal": { "type": "boolean" }
  },
  "if": {
    "properties": {
      "keiner": { "const": true }
    }
  },
  "then": {
    "properties" : {
      "abdominal": { "const": false },
      "zervikal": {"const": false }
    }
  },
  "else": {
    "properties": {
      "anyOf": [
        { "abdominal": { "const": true } },
        { "zervikal": { "const" : true } }
      ]
    }
  }
}

But the Newtonsoft online validator gives the error message

Unexpected token encountered when reading value for 'anyOf'. Expected StartObject, Boolean, got StartArray.

for the line in which ´anyOf´ starts. This confuses me, as all examples I can find show anyOf followed by an array of options.

So what am I doing wrong? Why cannot I have a startArray after anyOf, and how do I write the schema correctly?


Solution

  • I guess this is the schema you are looking for:

    Corrected JSON schema in JSONBuddy