6

Problem

I want to use json schema draft 7 to validate that an array contains several unordered objects. For example, the array should contains student A, B, regardless of their orders.

[{"name": "A"}, {"name": "B"}] //valid
[{"name": "B"}, {"name": "A"}] //valid
[{"name": "A"}, {"name": "C"}, {"name": "B"}] //extra students also valid
[] or [{"name": "A"}] or [{"name": "B"}] //invalid

Current Attempt

json schema contains keyword doesn't support a list

json schema Tuple validation keyword must be ordered

1 Answer 1

7

You want the allOf applicator keyword. You need to define multiple contains clauses.

allOf allows you to define multiple schemas which must all pass.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "allOf": [
    {
      "contains": {
        "required": ["name"],
        "properties": {
          "name": {
            "const": "A"
          }
        }
      }
    },
    {
      "contains": {
        "required": ["name"],
        "properties": {
          "name": {
            "const": "B"
          }
        }
      }
    }
  ]
}

Live demo here.

Sign up to request clarification or add additional context in comments.

3 Comments

You should put a required and a type in each of those, too.
required is necessary, but type is not required because const doesn't care about type. BUT, adding type couldn't hurt, and it shows intent.
Updated answer to reflect suggested changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.