Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-value enum in JSON schema?

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.

like image 449
Golo Roden Avatar asked Jan 19 '17 08:01

Golo Roden


2 Answers

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

like image 53
Ben Schenker Avatar answered Oct 02 '22 12:10

Ben Schenker


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 ☺️

like image 37
Golo Roden Avatar answered Oct 02 '22 12:10

Golo Roden