Conditional Json Schema validation based on property value

百般思念 提交于 2019-12-09 13:37:36

问题


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" }
        ]
    }
}


来源:https://stackoverflow.com/questions/36830827/conditional-json-schema-validation-based-on-property-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!