JSON Schema validation for a complex comination of AND/OR

Viewed 26

Similar to this question. But it's a little more complicated because I need to validate fields in a list of objects.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "All the Fruits",
  "type": "object",

  "properties":
  {
    "fruit":
    {
      "enum":
      [
        "apple",
        "orange",
        "banana",
        "watermelon",
        "all_fruit"
      ]
    }
  },

  "required":
  [
    "fruit"
  ],

  "additionalProperties": false
}

And it's used here in a different file:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Fruit basket",
    "type": "object",

    "properties":
    {
        "type":
        {
            "enum":
            [
                "fruit_basket"
            ]
        },
        "fruits":
        {
            "description": "List of fruits",
            "type": "array",
            "items":
            {
                "$ref": "fruit/fruits.schema.json#"
            },
            "uniqueItems": true,
           {
              // What do I add here?
           }
          
        }

            "required":
            [
                "fruits"
            ]

    "additionalProperties": false
}

Is there a way to validate JSON such that I can pick any subset of fruits or "all_fruit" not both.

Valid cases:

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

Invalid:

["all_fruit", "apple"]

all_fruit cannot exist with anything else.

Edit:

I tried this:

...
...
  "uniqueItems": true,
            "if" : {
                "properties": {
                    "fruits": {
                        "const": "all_fruit"
                    }
                }
            },
            "then": {
                "maxItems": 1,
                "minItems": 1
            }
...
...

But the condition seems to be satisfied always. Even when I don't use all_fruit and the validation errors out saying maxItems expected is 1.

1 Answers
Related