146

I want to describe with JSON schema array, which should consist of zero or more predefined values. To make it simple, let's have these possible values: one, two and three.

Correct arrays (should pass validation):

[]
["one", "one"]
["one", "three"]

Incorrect:

["four"]

Now, I know the "enum" property should be used, but I can't find relevant information where to put it.

Option A (under "items"):

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}

Option B:

{
    "type": "array",
    "items": {
        "type": "string"
    },
    "enum": ["one", "two", "three"]
}
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
senasi
  • 1,564
  • 2
  • 11
  • 12
  • 2
    **Docs**: [Enumerated Values](https://json-schema.org/understanding-json-schema/reference/generic.html?highlight=enum#enumerated-values) – KyleMit Jul 05 '20 at 17:02

2 Answers2

197

Option A is correct and satisfy your requirements.

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
28

According to json-schema documentation, the enumerated values of an array must be included in the "items" field:

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}

If you have an array that can hold e.g. items of different type, then your schema should look like the one below:

{
  "type": "array",
  "items": [
    {
      "type": "string",
      "enum": ["one", "two", "three"]
    },
    {
      "type": "integer",
      "enum": [1, 2, 3]
    }
  ]
}
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
  • 3
    That second example doesn't allow the array to contain two different types. It is tuple validation[1], which constrains the first and second items in the array to match the first and second schemas in the "items" array. [1] https://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation – Graham Lea Apr 18 '20 at 03:18
  • 9
    I think the proper construct to use in the second example is probably `anyOf`: https://json-schema.org/understanding-json-schema/reference/combining.html#anyof – Graham Lea Apr 18 '20 at 05:13
  • 1
    @GrahamLea I think you're right in earlier drafts (including the latest when you wrote your comment!) ... and I believe that as of the 2020-12 draft, to avoid this source of confusion, to specify tuples (in this example [string,int]), one now uses "prefixItems" instead of "items", which makes it easier not to get this wrong, and to see the difference between "any element may be a string or an int" and "the first item must be a string, the second must be an int")! "An array in which each element must be either a specified integer enum, or a specified string enum" is still slightly tricky ... – William Gallafent Feb 16 '22 at 11:57