JSON Schema: array with exactly n elements of given sub-schemas

568 Views Asked by At

I'm trying to figure out how can I write a JSON Schema for an array which has to contain exactly 2 elements, where each of those elements conform to its own subschema. I've got no idea at all, since none of anyOf, allOf, oneOf don't suit well here.

Let's say that I've got ss1 and ss2 subschemas that define elements of type t1 and t2, respectively. How can I write a schema which will accept arrays that one element of type t1 (conforming to ss1) and another element of type t2 (conforming to ss2)?

1

There are 1 best solutions below

0
On BEST ANSWER

The items keyword has a special format just for this. Instead of the value being a schema, it can be an array of schemas. When items is used this way, the items in the array must conform to the corresponding schema in the items array of schemas. Here is a working example assuming t1 = string and t2 = integer.

{
  "type": "array",
  "items": [
    { "$ref": "#/definitions/ss1" },
    { "$ref": "#/definitions/ss2" }
  ],
  "minItems": 2,
  "maxItems": 2,
  "definitions": {
    "ss1": { "type": "string" },
    "ss2": { "type": "integer" }
  }
}