Make sure item property in array is unique in Json Schema?

No, it is not possible. From the docs, json-schema: ...a JSON based format for defining the structure of JSON data.

It is quite limited for making data values validation because it is not the purpose of the standard. Many people have asked this before because it is common to request a kind of "unique Id" feature. Unfortunately for those who need it, json-schema does not provides you with that.

So if you want to ensure uniqueness your only option is to have "name" as property keys instead of property values.


If refactoring the data structure is an option, the following approach may be helpful:

  • Replace the array by a map. This can easily be achieved by using an object with patternProperties. The pattern is a regular expression. Any object that matches the pattern will be validated against the schema of the pattern-property. A pattern matching any string >= 3 characters looks like this: "....*", but it seems that a trailing ".*" is always implied, so "..." works as well.
  • Adding additionalProperties:false is an additional step to enforce your constraint (minLength:3).
  • To enforce at least one element in your map (you were using minItems:1 for your array), replace minItems by minProperties.

... resulting in the schema below:

"root": {
  "type": "object", 
  "properties": {
    "elements": {
      "type": "object", 
      "patternProperties": {
        "...": {
          "type": "object", 
          "properties": {
            "url": {
              "type": "string"
            }
          }
        }
      }, 
      "additionalProperties": false, 
      "minProperties": 1
    }
  }
}

If a document like the following (excerpt) was matching your old schema,

"elements": [
  {
    "name": "abc", 
    "url": "http://myurl1"
  }, 
  {
    "name": "def", 
    "url": "http://myurl2"
  }, 
  {
    "name": "ghij", 
    "url": "http://myurlx"
  }
]

... a document like that (excerpt) will match the new schema:

"elements": {
  "abc": {
    "url": "http://myurl1"
  }, 
  "def": {
    "url": "http://myurl2"
  }, 
  "ghij": {
    "url": "http://myurlx"
  }
}

If your use-case can handle the added overhead, you can apply a transformation on the document to generate a reduced document, and then apply validation again with a separate mini schema on the reduced document.

Here are some links with information on Json transformation tools:

  • JSONata.
  • A SO thread on Json transformation.

Handling your example case would be very straightforward in JSONata.


For Ajv validator you can use custom JSON-Schema keyword uniqueItemProperties : ajv-validator/ajv-keywords