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
json schema contains
keyword doesn't support a list
json schema Tuple validation
keyword must be ordered
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With