speedplane
speedplane

Reputation: 16141

jsonschema: Unique Properties in an Object Array

I have a schema with an array, and I would like to ensure that one property in the array is unique to all other of the same properties in the array. Using uniqueItems only ensures the entire object is unique, not one particular property.

An example will make this question more clear. In the arrays below, I want the key to be unique in the array, but content does not have to be. How would I make a json schema so that below good_array passes but bad_array fails?

good_array = [
  {"key":1, "content":"foo"},
  {"key":2, "content":"bar"},
  {"key":3, "content":"foo"}
]

bad_array = [
  {"key":1, "content":"foo"},
  {"key":1, "content":"bar"},
  {"key":3, "content":"foo"}
]

Upvotes: 3

Views: 2768

Answers (2)

chris
chris

Reputation: 445

Since the JSON Schema standard does not support this I created a Python package (JsonVL) that supports unique constraints on values in objects in an array.

It can be installed with pip install jsonvl

And then run with:

from jsonvl import validate

validate(data, schema)

Code examples in the GitHub repo: https://github.com/gregorybchris/jsonvl

Upvotes: 1

Relequestual
Relequestual

Reputation: 12355

This is not possible with JSON Schema. Sorry.

Two JSON instances are said to be equal if and only if they are of
the same type and have the same value according to the data model.
Specifically, this means:

  both are null; or

  both are true; or

  both are false; or

  both are strings, and are the same codepoint-for-codepoint; or

  both are numbers, and have the same mathematical value; or

  both are arrays, and have an equal value item-for-item; or

  both are objects, and each property in one has exactly one
  property with a key equal to the other's, and that other property
  has an equal value.

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01#section-4.2.3

Upvotes: 3

Related Questions