xdrew
xdrew

Reputation: 123

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?

Upvotes: 2

Views: 1450

Answers (2)

xdrew
xdrew

Reputation: 123

For those who can't use @esp handy syntax, here's an old style solution:

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

Upvotes: 1

esp
esp

Reputation: 7687

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).

Upvotes: 2

Related Questions