【问题标题】:JSON schema which allows either an object or an array of those objectsJSON 模式,它允许一个对象或这些对象的数组
【发布时间】:2016-04-04 21:16:49
【问题描述】:

假设我有一个 JSON 模式,它允许这样的对象:

...
  "assetMetadata": {
    "type": "object",
    "additionalProperties": false,
    "properties": { ... }
  }
...

假设我想更改它以允许相同的对象或该特定对象的数组。这里只接受一个数组:

...
"assetMetadata": {
  "type": "array",
  "description": "...",
  "items": {
    "type": "object",
    "additionalProperties": false,
    "properties": {...}
}
...

属性是相同的(它是同一个对象,只是多个而不是一个的选项)。

有趣的是,在我正在处理的项目中,解组器已经可以处理两者(它将单个对象变成大小为 1 的序列),因此纯粹是验证阻止了我继续前进。我们希望保持与现有 API 的可比性,这就是我现在不能只需要数组的原因。

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    您可以使用anyOf 关键字和definitions/$ref 来避免重复。

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "assetMetadata": {
          "anyOf": [
            { "$ref": "#/definitions/assetMetaData" },
            {
              "type": "array",
              "description": "...",
              "items": { "$ref": "#/definitions/assetMetaData" }
            }
          ]
        }
      },
      "definitions": {
        "assetMetadata": {
          "type": "object",
          "additionalProperties": false,
          "properties": { ... }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2020-02-09
      • 1970-01-01
      相关资源
      最近更新 更多