From 6d84fb43162c226a05a34c508d407bc5b8c698a1 Mon Sep 17 00:00:00 2001 From: danielyan Date: Mon, 9 Feb 2026 20:02:13 +0000 Subject: [PATCH] Include duplicate indices and value in uniqueItems error message When uniqueItems validation fails, the error message now includes which items are duplicated and at what indices. For example: [1, 2, 3, 2, 5] has non-unique elements (items at index 1 and 3 are equal: 2) This helps users quickly identify duplicates in large arrays without post-processing the validation result. Closes #1363 --- jsonschema/_keywords.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/jsonschema/_keywords.py b/jsonschema/_keywords.py index f30f95419..14e977af0 100644 --- a/jsonschema/_keywords.py +++ b/jsonschema/_keywords.py @@ -209,7 +209,28 @@ def uniqueItems(validator, uI, instance, schema): and validator.is_type(instance, "array") and not uniq(instance) ): - yield ValidationError(f"{instance!r} has non-unique elements") + # Find the first pair of duplicate items and their indices + seen = [] + indices = None + for i, item in enumerate(instance): + for j, seen_item in enumerate(seen): + if equal(item, seen_item): + indices = (j, i) + break + if indices is not None: + break + seen.append(item) + + if indices is not None: + first, second = indices + msg = ( + f"{instance!r} has non-unique elements" + f" (items at index {first} and {second}" + f" are equal: {instance[first]!r})" + ) + else: + msg = f"{instance!r} has non-unique elements" + yield ValidationError(msg) def pattern(validator, patrn, instance, schema):