如何在 json-schema 中定义 属性 选择

How to define property choice in json-schema

我需要为 属性 选择的对象创建一个 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 属性 是一个 object,当函数为 string - kosfn 为 null。但是我不知道如何构建一个涵盖这两种情况的模式,因为 oneOf 不能应用于属性。

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

您可以(并且应该)将每个子模式之间相同的定义提取到父模式中。我已经留下了您提供的两个子模式,以明确完成了什么。