kevin807210561
kevin807210561

Reputation: 67

validate array json contains several unordered objects using json schema

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

Upvotes: 6

Views: 2173

Answers (1)

Relequestual
Relequestual

Reputation: 12295

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.

Upvotes: 7

Related Questions