bhantol bhantol - 1 year ago 120
JSON Question

json schema field required based on value of nested field

I have tried JSON Schema - specify field is required based on value of another field but it does not work for me for the following situation.

instance 1

{

"part1": {
"subPartA" : {
"value": "X"
}
},
"partX": {
"propXX": "val1",
"prop2": null

}
}


instance 2

{

"part1": {
"subPartA" : {
"value": "Y"
}
},
"partY": {
"propYY": "val123",
"prop2": null

}
}


How does one make
partX.propXX
required if
part1.subPart1.value = "X"

AND
partY.propYY
required if
part1.subPart1.value = "Y"


?

esp esp
Answer Source

Unless you mean that you want the value in data to be part of required property name (which is not possible using JSON-schema keywords), you can do this correlation:

{
  "type": "object",
  "required": ["part1"],
  "properties": {
    "part1": {
      "type": "object",
      "required": ["subPartA"],
      "properties": {
        "subPartA": {
          "type": "object",
          "required": ["value"],
          "properties": {
            "value": {
              "type": "string"
            }
          }
        }
      }
    }
  },
  "anyOf": [
    {
      "required": ["partX"],
      "properties": {
        "part1": {
          "properties": {
            "subPartA": {
              "properties": {
                "value": {
                  "enum": ["X"]
                }
              }
            }
          }
        },
        "partX": {
          "type": "object",
          "required": ["propXX"],
          "properties": {
            "propXX": {
              "type": "string"
            }
          }
        }
      }
    },
    {
      "required": ["partY"],
      "properties": {
        "part1": {
          "properties": {
            "subPartA": {
              "properties": {
                "value": {
                  "enum": ["Y"]
                }
              }
            }
          }
        },
        "partY": {
          "type": "object",
          "required": ["propYY"],
          "properties": {
            "propYY": {
              "type": "string"
            }
          }
        }
      }
    }
  ]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download