Correct way to define array of enums in JSON schema

117,731

Solution 1

Option A is correct and satisfy your requirements.

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

Solution 2

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]
    }
  ]
}
Share:
117,731

Related videos on Youtube

senasi
Author by

senasi

Updated on November 09, 2020

Comments

  • senasi
    senasi over 3 years

    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"]
    }
    
  • Graham Lea
    Graham Lea about 4 years
    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] json-schema.org/understanding-json-schema/reference/…
  • Graham Lea
    Graham Lea about 4 years
    I think the proper construct to use in the second example is probably anyOf: json-schema.org/understanding-json-schema/reference/…
  • William Gallafent
    William Gallafent about 2 years
    @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 ...