Search code examples
jsonjsonschema

JSON schema child conditional implementation


I've looked through the previous questions and can't seem to find the specific scenario, so apologies if you've seen this question before.

For brevity sake, I have the follow JSON

{
  "minimum": 123,
  "charges":[
    {"amount": 123, "billable": 456},
    {"amount": 234, "billable": 456},
  ]
}
  1. "minimum" is optional initially,
  2. both "amount" and "billable" are optional
  3. If "amount" is present in any of the objects in the "charges" array, then "minimum" is now required.

The following would be invalid:

{
  "charges":[
    {"billable": 456},
    {"amount": 234, "billable": 456}, // amount is present here, so "minimum" needs to be on the root node.
  ]
}

The following is valid:

{
  "charges":[
    {"billable": 456},
    {"billable": 456},
  ]
}

Is this behavior possible? Thank you, brain trust.


Solution

  • Given your requirements you would need to use the if and required keywords.

    {
      "if": {
        "type": "object",
        "properties": {
          "charges": {
            "type": "array",
            "items": {
              "not": {
                "required": [
                  "amount"
                ]
              }
            }
          }
        }
      },
      "else": {
        "required": [
          "minimum"
        ]
      }
    }