4

I am developing a JSON Schema for validating documents like this one:

{
    "map": [

        {
            "key": "mandatoryKey1",
            "value": "value1"
        },
        {
            "key": "mandatoryKey2",
            "value": "value2"
        },
        {
            "key": "otherStuff",
            "value": "value3"
        },
        {
            "key": "someMoreStuff",
            "value": "value4"
        }
    ]
}

The document needs to have a "map" array with elements containing keys and values. There MUST be two elements with mandatoryKey1 and mandatoryKey2. Any other key-value pairs are allowed. Order of the elements should not matter. I found this difficult to express in JSON Schema. I can force the schema to check for the mandatory keys like this (left out the definitions part as it is trivial) :

"map": {
    "type": "array",
    "minItems": 2,
    "items": {
        "oneOf": [
            {
                "$ref": "#/definitions/mandatoryElement1"
            },
            {
                "$ref": "#/definitions/mandatoryElement2"
            }
        ]
    }
}

The problems are:

  • It validates that a document includes the mandatory data, but does not permit any other key/value pairs.
  • It does not check for duplicates, so it can cheated by including mandatoryElement1 twice. Uniqueness of items can only be checked by tuple validation, which I cannot apply here cause the item order should not matter.

The basic problem I see here is that the array elements somehow need to know about each other, i.e. arbitrary key/value pairs are allowed ONLY IF the mandatory keys are present. This "conditional validation" does not seem to be possible with JSON Schema. Any ideas for a better approach?

dschuld
  • 89
  • 12
  • https://stackoverflow.com/questions/38717933/jsonschema-attribute-conditionally-required – tom redfern Dec 04 '19 at 15:49
  • Thanks @tomredfern but I cannot see how these solutions are applicable here, as they apply to conditional existence of properties, not array elements like here. – dschuld Dec 04 '19 at 16:08
  • Sorry I posted the comment before actually reading your question properly – tom redfern Dec 04 '19 at 16:20
  • 2
    THis looks VERY similar to this question I answered earlier today: https://stackoverflow.com/q/59176042/89211 – Relequestual Dec 04 '19 at 17:28
  • 1
    "It does not check for duplicates" This sounds like something that JSON Schema doesn't support, though there is an open issue for it. https://github.com/json-schema-org/json-schema-spec/issues/538 – gregsdennis Dec 04 '19 at 18:32
  • @Relequestual that pretty much solves what I was looking for, thanks a lot! – dschuld Dec 05 '19 at 10:32

0 Answers0