2

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for clarifying those things)
1

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"]}}}}}}
    ]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.