S.A.
S.A.

Reputation: 2151

JSON Schema: Conditionally require property depending on several properties' values

I want to validate a JSON file using JSON schema, several "properties" should be required depending on what values some other properties have.

Example

I have seen a very helpful answer here: https://stackoverflow.com/a/38781027/5201771 --> there, the author addresses how to solve this problem for the case of a single property (e.g., only "A" has value "foo", so require "C").

However, I currently don't see how to extend that answer to my case, where several properties determine the outcome.

Example Files

for illustration, I supply some files that should pass or fail the validation:

should pass:

{
    "A": "bar"
    "B": "baz"
}
{
    "A": "foo"
    "C": "some value"
}
{
    "A": "bar"
    "B": "foo"
    "D": "some value"
}

should fail:

{
    "A": "foo"
    "B": "foo"
    "D": "some value"
}

Upvotes: 0

Views: 99

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24409

You can combine conditionals a number of ways, but combining them with allOf is usually the best way.

{
  "type": "object",
  "properties": {
    "A": {},
    "B": {},
    "C": {},
    "D": {}
  },
  "allOf": [
    { "$ref": "#/definitions/if-A-then-C-is-required" },
    { "$ref": "#/definitions/if-B-then-D-is-required" }
  ],
  "definitions": {
    "if-A-then-C-is-required": {
      "if": {
        "type": "object",
        "properties": {
          "A": { "const": "foo" }
        },
        "required": ["A"]
      },
      "then": { "required": ["C"] }
    },
    "if-B-then-D-is-required": {
      "if": {
        "type": "object",
        "properties": {
          "B": { "const": "foo" }
        },
        "required": ["B"]
      },
      "then": { "required": ["D"] }
    }
  }
}

Upvotes: 2

Related Questions