JSON schema AND/OR for array enum

Viewed 155

I'd like to specify JSON schema to restrict combinations of array values.

For example if I have an array where the values could be "apple", "orange" or "banana", but "apple" and "orange" would never appear together.

i.e. these are all valid

[]
["apple"]
["orange"]
["banana"]
["apple, "banana"]
["orange", "banana"]

but these are NOT valid:

["apple","orange"]
["apple","orange","banana"]

I've got as far as the an enum array, but I'm not sure whether I can specify an OR operator somehow:

"options": 
{
  "type": "array",
  "items": {
    "type": "string",
    "enum": [
      "apple",
      "orange", 
      "banana"
    ]
  }
}

p.s. ["apple","apple"] would also be invalid, but perhaps that's another story.

1 Answers

You need to use a combination of not, allOf, and contains.

not inverts the validation result.

allOf requires that all of the subschemas are valid.

contains requires that the array contains an item that is valid according to the subschema value.

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "type": "array",
  "items": {
    "type": "string",
    "enum": ["apple","orange","banana"]
  },
  "not": {
    "allOf": [
      {
        "contains": {
          "const": "apple"
        }
      },
      {
        "contains": {
          "const": "orange"
        }
      }
    ]
  }
}

Live demo: https://jsonschema.dev/s/C835R

Related