MondoD
MondoD

Reputation: 13

How to make items required in an array using JSON Schema?

I have an string array and I don't know if I can set required items for it or not.

For "type":"object", it can set "required" to make items be necessary, but I don't know how to it for string array.

This is my json example:

{
  "sets": ["B", "A", "C", "_A", "Y", "_B"]
}

"A", "B", "C" are required,
"X", "Y", "Z" are optional,
any items starting with "_" are optional also,
all items are unique.
Reject all other items if it doesn't match this rule.


This is my json schema, but I don't know how to set required items for this array.

{
    "type": "object",
    "properties": {
      "sets": {
        "type": "array",
        "items": {
          "type": "string",
          "oneOf": [
            {"enum": ["A", "B", "C", "X", "Y", "Z"]},
            {"pattern": "^_"}
          ]
        },
        "uniqueItems": true
      }
    }
}

Hope you can understand my English, if you need more information or a better title, just tell me, thank you!

Upvotes: 1

Views: 731

Answers (1)

Relequestual
Relequestual

Reputation: 12355

This is quite an interesting and complex requirement, but there is a solution. It has some duplication, but I'm not sure there's an alternative approach.

You need to make sure A, B, and C are in the array...

"allOf": [
        { "contains": { "const": "A" } },
        { "contains": { "const": "B" } },
        { "contains": { "const": "C" } }
      ],

This was the only part you were missing. The contains keyword makes sure the array contains an item which is valid according to the subschema. Location is not important.

Here's the full schema, and a demo: https://jsonschema.dev/s/jVSAG

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "type": "object",
  "properties": {
    "sets": {
      "type": "array",
      "allOf": [
        { "contains": { "const": "A" } },
        { "contains": { "const": "B" } },
        { "contains": { "const": "C" } }
      ],
      "items": {
        "oneOf": [
          { "enum": ["A", "B", "C", "X", "Y", "Z"] },
          { "pattern": "^_" }
        ]
      },
      "uniqueItems": true
    }
  }
}

Upvotes: 2

Related Questions