1

I've a JSON Schema and a sample input. I need to write a generic schema which can handle the array regardless the length of the array. Currently, I need to write schema for each of the index in the array.

JSON Schema

{
  "title":"Example",
  "$schema":"http://json-schema.org/draft-04/schema#",
  "type":"array",
  "items":[
    {
     "oneOf":[
       {
         "multipleOf": 3
       }
     ]
    },
    {
      "oneOf":[
       {
         "multipleOf": 3
       },
       {
         "multipleOf": 5
       }
     ]
    }
  ]
}

Sample Input

[
  3,
  5
]

I need a schema which can validate [1,3,5,6,3,5,4,......] (regardless the length)

1 Answer 1

2

If you put a schema directly in items, instead of using an array, then it applies to all array items:

{
    "type": "array",
    "items": {
        "oneOf": [
            {"multipleOf": 3},
            {"multipleOf": 5}
        ]
    }
}

If you want to describe an initial set of items with specific schemas, and all the following ones with a generic one, then use an array with items, and a schema in additionalItems:

{
    "type": "array",
    "items": [
        {"multipleOf": 3},
        ...
    ],
    "additionalItems": {
        "oneOf": [
            {"multipleOf": 3},
            {"multipleOf": 5}
        ]
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

What if I want a schema to validate a array in which the '0'th index of the array should be multiple of 2 and rest can have both multiples of 2 and 5. And the '0'th index is required.
You will also need to include "minItems": 1 to make the '0'th index required.
For the second schema with additionalItems the input [3,7] is getting validated. It should not be ryt?
what if the array can contain a single null value like this [ null ]

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.