Search code examples
jsonschemajson-schema-validatorjson-schema-defaults

json-schema - allow for logical-OR in required properties


An alternate title for this question would be "required property combinations".

Say I am working with a json-schema like so:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "JSON schema for NLU (npm-link-up) library.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "list", "packages", "deps"
  ],
   // ... 
}

what I want to do, is make one of "list", "packages", "deps", to be required. That is one, but no more than one, should be present.

So it might be something like:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "JSON schema for NLU (npm-link-up) library.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    {
      "min": 1,
      "max": 1,
      "selection":  ["list", "packages", "deps"]
    }
  ],
}

or

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "JSON schema for NLU (npm-link-up) library.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    {
      "operator": "or",
      "selection": ["list", "packages", "deps"]
    }
  ],
}

is this possible?


Solution

  • There are four boolean combinator keywords in JSON Schema:

    • allOf - AND
    • anyOf - OR
    • oneOf - XOR (eXclusive OR)
    • not - NOT

    What you want can be done like this ...

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "JSON schema for NLU (npm-link-up) library.",
      "type": "object",
      "additionalProperties": false,
      "oneOf": [
        { "required": ["list"] },
        { "required": ["packages"] },
        { "required": ["deps"] }
      ]
    }