Einar Sundgren
Einar Sundgren

Reputation: 4433

Create JSON Schema value dependency

I have a JSON schema I want to change by a dependency of one of the values of the JSON structure. For example if {"foo":1} also include {"fooBar":"number"} in the schema, resulting in {"foo":"number", "fooBar":"number"} but if {"foo":2} instead include {"fooBar2":"bool", "fooBar3":"string"} resulting in {"foo":1, "fooBar2":"bool", "fooBar3":"string"}. Is this possible.

I know how to make the inclusion of a key change the schema (code example from here) but I cannot find any example on how this could be done using values. If this is even possible.

 {
  "type": "object",

  "properties": {
    "name": { "type": "string" },
    "credit_card": { "type": "number" },
    "billing_address": { "type": "string" }
  },

  "required": ["name"],

  "dependencies": {
    "credit_card": ["billing_address"]
  }
}

Upvotes: 0

Views: 359

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

It can be done, but it's a little complicated. Below is the general pattern.

{
  "type": "object",
  "anyOf": [
    {
      "properties": {
        "foo": { "enum": [1] },
        "fooBar": { "type": "number" }
      }
    },
    {
      "properties": {
        "foo": { "enum": [2] },
        "fooBar2": { "type": "boolean" },
        "fooBar3": { "type": "string" }
      }
    }
  ]
}

Upvotes: 2

Related Questions