0

I have a JSON object as blow:

{
  "a": {
    "key1": "value1",
    "key2": true
  },
  "b": {
    "key3": "value3",
    "key4": "value4" // make key4 required if the value of key2 is true, otherwise it should be optional
  }
}

What I need is to make key4 required if the value of key2 is true, otherwise it should be optional. I know that JSON schema support optional required based on the value of keys within the same object. But in this case, what I need to base on the value of a key from another object.


.

Allen Wang
  • 107
  • 1
  • 9

1 Answers1

1

This works the same way as it does with a flat structure. The if and then keywords are just schemas that apply to the instance. So, if you want to define nested conditions or nested constraints you just need to define a schema that expresses those constraints.

{
  "if": {
    "properties": {
      "a": {
        "properties": {
          "key2": { "const": true }
        },
        "required": ["key2"]
      }
    },
    "required": ["a"]
  },
  "then": {
    "properties": {
      "b": { "required": ["key4"] }
    }
  }
}
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53