xdrew xdrew - 16 days ago 6
JSON Question

Json schema check all items enum are present in array of objects

I have json schema like this:

{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": {
"type": "object",
"properties": {
"country": {
"type": "string",
"maxLength": 2,
"enum": ["aa", "bb"]
}
},
"required": [
"country"
]
}
}


And json in this format:

[
{"country": "aa"},
]


I want schema to check whether the json file contains all countries listed in enum:

[
{"country": "aa"},
{"country": "bb"},
]


Is it possible?

esp esp
Answer

You can do it with v5/6 contains keyword:

{
  "allOf": [
    { "contains": { "properties": { "country": { "constant": "aa" } } } },
    { "contains": { "properties": { "country": { "constant": "bb" } } } }
  ]
}

"constant": "aa" is another v5/6 keyword, same as "enum": ["aa"]. At the moment Ajv supports these keyword (a bit of self promotion).