Search code examples
jsonuniquejsonschema

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"}
]

Solution

  • 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