【问题标题】:How to define property choice in json-schema如何在 json-schema 中定义属性选择
【发布时间】:2020-08-05 13:10:26
【问题描述】:

我需要为对象的属性选择创建一个 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 不能应用于属性”是什么意思?

标签: jsonschema json-schema-validator


【解决方案1】:

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

您需要将两个模式嵌套到 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"
        }
      }
    }
  ]
}

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

【讨论】:

  • 是的,我没有意识到我可以创建一个属性数组并使用 oneOf。该解决方案工作正常。我想我可以概括这两个子模式。
  • 一旦您将其视为一个子模式数组,其中数组中的每个项目本身就是一个 JSON 模式,大量 JSON 模式就变得更容易了。
  • 模式(和子模式)应用于实例。应用程序关键字确定如何应用子模式,以及如何策划和修改结果。例如,properties 是一个应用程序关键字,其中对象中的每个值本身就是一个子模式。
猜你喜欢
  • 1970-01-01
  • 2017-04-22
  • 2018-10-16
  • 1970-01-01
  • 2022-12-17
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
相关资源
最近更新 更多