Conditional Json Schema validation based on proper

2019-03-31 23:54发布

问题:

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:

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

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