0

I have a simple object like that:

{
  "type": "object",
  "properties": {
    "channelName": {
      "type": "string",
      "enum": [
        "channel_type_A",
        "channel_type_B"
      ]
    },
    "channelDetails": {
      "type": "object",
      "oneOf": [
        TYPE_A,
        TYPE_B
      ]
    }
  }
}

TYPE_A and TYPE_B are two other irrelevant objects defined in the same file.

The point is that a json object like that:

{ 
"channelName" = "channel_type_A",
"channelDetails" = {TYPE_B}
}

is validated by the schema but I don't want to.
So, what I need is a schema that works like that:

  • if "channelName" == "channel_type_A" -> "channelDetails" is TYPE_A
  • if "channelName" == "channel_type_B" -> "channelDetails" is TYPE_B

I thought I could use dependencies, but I only saw examples that check if a property exists and don't make assumptions based on their values.
Is it possible to do what I want with json schema?

zx485
  • 28,498
  • 28
  • 50
  • 59

1 Answers1

0

Try this,

{
  "type": "object",
  "properties": {
    "channelName": {
      "type": "string",
      "enum": [
        "channel_type_A",
        "channel_type_B"
      ]
    },
    "channelDetails": {
      "type": "object",
      "if": {
        "properties": {
          "channelName": {
            "const": "channel_type_A"
          }
        }
      },
      "then": {
        "$ref": "#/definitions/TYPE_A"
      },
      "else": {
        "$ref": "#/definitions/TYPE_B"
      }
    }
  },
  "definitions": {
    "TYPE_A": {
      "type": "object",
      "properties": {
        // Properties and validation specific to TYPE_A
      }
    },
    "TYPE_B": {
      "type": "object",
      "properties": {
        // Properties and validation specific to TYPE_B
      }
    }
  }
}

In the schema above, the if keyword checks if the value of the channelName property is channel_type_A. If the condition is true, the then keyword references the schema definition TYPE_A. Otherwise, if the condition is false, the else keyword references the schema definition TYPE_B.

You can replace the comments with the actual properties and validation specific to TYPE_A and TYPE_B objects.

By using this schema, any JSON object that doesn't match the expected channelDetails schema based on the value of channelName will fail the validation.

MUsmanTahir
  • 75
  • 10
  • Thank you for your answer but it's still not working 100% correctly. It seems that the if statement is always validated whatever I put as channelName value. So, it always wants an object of TYPE_A even if channelName is "channel_type_B". Do you have any guesses? – Silvia di Luise Jun 12 '23 at 09:32