简体   繁体   中英

JSON Schema: array where non-null elements are unique

I am trying to construct a JSON schema that meets the following:

  1. Declares a top-level object with at least one property
  2. The value of each property will be an array, each of which must contain exactly N items
  3. Array items must be integers taken from the closed interval [J, K] , or null
  4. Integer items in each array must be unique within that array
  5. There is no uniqueness constraint applied to null (so no implied relationship between N and the interval size KJ )

The problem I am running into is #4 and #5. It is easy enough to meet the first 3 requirements, plus part of the 4th, using this schema:

{
  "$schema": "http://json-schema.org/draft/2019-09/schema#",
  "type": "object",
  "minProperties": 1,
  "additionalProperties": {
    "type": "array",
    "minItems": N,
    "maxItems": N,
    "items": {
      "anyOf": [
        {
          "type": "integer",
          "minimum": J,
          "maximum": K
        },
        {
          "type": "null"
        }
      ]
    },
    "uniqueItems": true
  }
}

I am not sure how (or if it's even possible) to specify an array that applies the uniqueItems constraint to only a subset of the allowable items. I tried moving uniqueItems to lower levels of the schema with the hope that it might operate with restricted scope, but that doesn't work.

This might be possible using conditionals, but I haven't gone down that road yet since I'm not sure it will actually work, and I am hoping there is an easier approach that I have overlooked.

So, my question is: Is there a way to specify a JSON schema array that selectively enforces a uniqueness constraint only on the items that are not null ?

this is beyond the capabilities of uniqueItems and not a constraint JSON Schema is able to express. you will need to check this requirement elsewhere in your application's business logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM