Coder
Coder

Reputation: 3272

Conditional Json Schema validation based on property value

I have the input json like below,

{
  "results": [
    {
      "name": "A",
      "testA": "testAValue"
    }
  ]
}

the condition is, if value of 'name' is 'A', then 'testA' should be the required field and if value of 'name' is 'B', then 'testB' should be the required field.

This is the Json Schema I tried and its not working as expected,

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": [
    "results"
  ],
  "properties": {
    "results": {
      "type": "array",
      "oneOf": [
        {
          "$ref": "#/definitions/person"
        },
        {
          "$ref": "#/definitions/company"
        }
      ]
    }
  },
  "definitions": {
    "person": {
      "type": "object",
      "required": [
        "name",
        "testA"
      ],
      "properties": {
        "name": {
          "type": "string",
          "enum": [
            "A"
          ]
        },
        "testA": {
          "type": "string"
        }
      }
    },
    "company": {
      "type": "object",
      "required": [
        "name",
        "testB"
      ],
      "properties": {
        "name": {
          "type": "string",
          "enum": [
            "B"
          ]
        },
        "testB": {
          "type": "string"
        }
      }
    }
  }
}

Tried with "dependecies" in JSON Schema too but wasn't able to find the correct solution.

Any help / workaround with Sample JSON Schema to achieve the above use case is appreciated.

Upvotes: 4

Views: 4858

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

Your're close. Your oneOf needs to be in the items keyword.

{
    "type": "array",
    "items": {
        "oneOf": [
            { "$ref": "#/definitions/person" },
            { "$ref": "#/definitions/company" }
        ]
    }
}

Upvotes: 4

Related Questions