Correct way to define array of enums in JSON schema

ArraysJsonEnumsJsonschema

Arrays Problem Overview


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

Arrays Solutions


Solution 1 - Arrays

Option A is correct and satisfy your requirements.

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

Solution 2 - Arrays

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsenasiView Question on Stackoverflow
Solution 1 - ArraysjruizarangurenView Answer on Stackoverflow
Solution 2 - ArraysGiorgos MyrianthousView Answer on Stackoverflow