delpo
delpo

Reputation: 239

JSON Schema validate array filtering its elements

I'm trying to validate an array of objects property that contains at least 3 items that matches:

x.foo == 'bar'.

For example

{
    ...
    array: [
        { id: 1, foo: 'bar'}, { id: 2, foo: 'bar' }, {id: 3, foo: 'bar'}, { id: 4, foo: 'not-bar'}
    ]
}

This matches because there are at least 3 items where foo == 'bar' is true.

In other words, I'm trying to figure out how to filter an array property and then validate its length with certain conditions.

Is there a standard way to do this using JSON schema?

Upvotes: 0

Views: 280

Answers (1)

erosb
erosb

Reputation: 3141

In the latest draft (2020-12) there is "minContains" keyword that you can use here, together with "contains" and "const":

{
  "minContains": 3,
  "contains": {
    "type": "object",
    "properties": {
      "foo": {
        "const": "bar"
      }
    }
  }
}

Upvotes: 2

Related Questions