如何在json模式中定义属性选择

时间:2020-08-05 13:10:26

标签: jsonschema json-schema-validator

我需要为对象的属性选择创建一个Json模式 第一个选项是:

"part_2_2_object_details_array": {
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "function": {
            "type": "null"
        },
        "address": {
            "type": "string"
        },
        "kosfn": {
            "$ref": "#/definitions/kosfn"
        }
    }
}

第二个是:

"part_2_2_object_details_array": {
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "function": {
            "type": "string"
        },
        "address": {
            "type": "string"
        },
        "kosfn": {
            "type": "null"
        }
    }
}

当函数为 null -kosfn属性为对象时,当函数为 string -kosfn为 null >。但是由于oneOf不能应用于属性,因此我无法弄清楚如何构建一种涵盖两种情况的模式。

1 个答案:

答案 0 :(得分:0)

oneOf的值必须是一个数组,其中每个项目都是JSON模式(子模式)。

您需要将两个架构嵌套到oneOf ...的子模式中。

实时演示:https://jsonschema.dev/s/ssosr

{
  "definitions": {
    "kosfn": true
  },
  "type": "object",
  "oneOf": [
    {
      "properties": {
        "name": {
          "type": "string"
        },
        "function": {
          "type": "null"
        },
        "address": {
          "type": "string"
        },
        "kosfn": {
          "$ref": "#/definitions/kosfn"
        }
      }
    },
    {
      "properties": {
        "name": {
          "type": "string"
        },
        "function": {
          "type": "string"
        },
        "address": {
          "type": "string"
        },
        "kosfn": {
          "type": "null"
        }
      }
    }
  ]
}

您可以(并且应该)将每个子模式之间相同的定义提取到父模式中。当您提供这两个子方案时,我已经将它们清楚地说明了已完成。

相关问题