uniqueItems : Boolean
uniqueItems
BooleanIf this keyword is set to the boolean value true, the instance validates successfully if all of its elements are unique.
Kind | Assertion |
---|---|
Applies To | Array |
Dialect | 2020-12 |
Introduced In | Draft 2 |
Vocabulary | Validation |
Specification | https://json-schema.org/draft/2020-12/json-schema-validation.html#section-6.4.3 |
Metaschema | https://json-schema.org/draft/2020-12/meta/validation |
Also see |
|
The uniqueItems
keyword is used to ensure that all the items in an array are unique. This keyword is particularly useful when you need to enforce that an array contains no duplicate elements.
- The value of this keyword must be a boolean.
- This keyword, when set to true, specifies that all elements in an array must be unique.
- If it is set to false, the array can contain duplicate items.
- Omitting this keyword has the same behavior as a value of false.
Examples
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "array",
"uniqueItems": true
}
[ 1, "hello", true ]
[ false, "world", 2, 2 ]
[ { "name": "John" }, false, "world", 2, { "name": "John" } ]
- Element uniqueness also deeply applies for complex structures like objects.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "array"
}
// or
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "array",
"uniqueItems": false
}
[ 1, "hello", true ]
[ false, "world", 2, 2 ]
uniqueItems
can be used with other array keywords likeitems
andprefixItems
to add more constraints to the instance. See the example below.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" }
},
"required": [ "id", "name" ]
},
"uniqueItems": true
}
[
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Doe" }
]
[
{ "id": 1, "name": "Jane" },
{ "id": 1, "name": "Jane" }
]