6

I have an array that contains strings, such as:

[ 'foo', 'bar' ]

The possible values are limited. For example, valid values are foo, bar, and baz.

Now the array shall be valid when it contains only values that are valid, no value more than once, but it can have an arbitrary number of values.

Examples for valid arrays would be [ 'foo' ], [ 'foo', 'bar' ], and [ 'bar', 'baz' ]. Examples for invalid arrays would be [], [ 'foo', 'foo' ], and [ 'bar', 'something-else' ].

How can I do this validation using JSON schema? So far, I have figured out the array type which provides the minItems and the uniqueItems properties. What I could not yet figure out is: How to allow multiple (but only valid) values? I know that there is enum, but this only allows a single value, not multiple ones.

Can anybody help?

PS: Just in case it matters, I'm using the ajv module with Node.js to run the validation.

Golo Roden
  • 140,679
  • 96
  • 298
  • 425

2 Answers2

14

Spelling out the solution more clearly:

{
  "type": "array",
  "items": {
    "type": "string",
    "enum": [ "foo", "bar", "baz" ]
  },
  "uniqueItems": true,
  "minItems": 1
}

See: https://spacetelescope.github.io/understanding-json-schema/reference/array.html

Ben Schenker
  • 869
  • 9
  • 10
  • `"type": "string"` can be removed from line 4. https://json-schema.org/understanding-json-schema/reference/generic.html#enumerated-values – ffxsam May 26 '21 at 01:56
2

Okay, I got it by myself…

You need to provide the items property as well, and then for each item define that it needs to be of type: 'string' and its value to be an enum: [ 'foo', 'bar', 'baz' ].

This way you ensure that each single items is a string with a valid value, and then you enforce this for the entire array ☺️

Golo Roden
  • 140,679
  • 96
  • 298
  • 425