json schema to validate property value with its dynamic key

838 views Asked by At

data:

{
  "dynamic_key_1": {
    "key1": "value1"
    "id": "dynamic_key_1"
  },
  "dynamic_key_2": {
    "key1": "value2"
    "id": "some_random"
  }
}

schema:

{
    "patternProperties": {
      "^[^{}\"/\\\\]+$": {
        "type": "object",
        "required": [
          "id"
        ],
        "properties": {
          "id": {
            "type": "string"
            // ... validate with key
          }
        }
     }
  }
}

How to validate the id value to equal it's key using json schema.

In above case the dynamic_key_1 would pass and dynamic_key_2 would fail the test.

2

There are 2 answers

0
Relequestual On

It's not possible to do this in JSON Schema unless you know all possible values upfront. You cannot dynamically use data from the instance as some sort of template in the schema.

0
Sandeep On

I did find a way to do this. Used patternNames regex to validate.

...
"propertyNames": {
    "pattern": "[A-Za-z][A-Za-z0-9_-]*$"
  },
"patternProperties": {
      "^[^{}\"/\\\\]+$": {
        "type": "object",
        "required": [
          "id"
        ],
        "properties": {
          "id": {
            "type": "string"
            // ... validate with key
          }
        }
     }
  }
...