4

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.

1

1 Answer 1

4

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

{
    "type": "array",
    "items": {
        "oneOf": [
            { "$ref": "#/definitions/person" },
            { "$ref": "#/definitions/company" }
        ]
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.