2

I have the following schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "choices": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "value": {
            "type": "string"
          },
          "isCorrect": {
            "type": "boolean"
          }
        },
        "required": ["value", "isCorrect"],
        "additionalProperties": false
      },
      "minItems": 1,
      "maxItems": 50,
      "uniqueItems": true,
      "additionalItems": false,
    }
  }
}

Which validates data

{
  "choices": [
    {
      "value": "John",
      "isCorrect": true
    },
    {
      "value": "Doe",
      "isCorrect": true
    }
  ] 
}

But I want isCorrect to have a single true (others false) in the array of the objects.

Is it possible to validate the uniqueness on a single key?

1 Answer 1

3

You can't check uniqueness based on a key, but you can use a combination of contains and maxContains to have the constraint you described.

In the properties.choices object, add the following...

      "contains": {
        "properties": {
          "isCorrect": {
            "const": true
          }
        }
      },
      "maxContains": 1,

You can check this using https://json-schema.hyperjump.io

The contains keyword makes sure that the array contains at least one item that is valid according to the subschema value.

The maxContains keyword, if the contains keyword is used, makes sure no more that number of items are valid according to the contains subschema value.

https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-6.4.4

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.