Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate array json contains several unordered objects using json schema

Tags:

jsonschema

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

like image 991
kevin807210561 Avatar asked Dec 04 '19 12:12

kevin807210561


People also ask

How does JSON Schema validate JSON data?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

How would you define an array of objects in JSON Schema?

To do this, we use the prefixItems keyword. prefixItems is an array, where each item is a schema that corresponds to each index of the document's array. That is, an array where the first element validates the first element of the input array, the second element validates the second element of the input array, etc.

What is allOf in JSON Schema?

allOf: (AND) Must be valid against all of the subschemas. anyOf: (OR) Must be valid against any of the subschemas. oneOf: (XOR) Must be valid against exactly one of the subschemas.


1 Answers

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.

like image 198
Relequestual Avatar answered Oct 07 '22 00:10

Relequestual