【问题标题】:JSON schema definition with multiple sets of enums for array attribute具有数组属性的多组枚举的 JSON 模式定义
【发布时间】:2021-04-06 16:46:46
【问题描述】:

我想为一个对象创建一个 JSON 模式,其中一个属性被限制为多组枚举。

例如:

{
  "data": {
    "type": "myObject",
    "attributes": {
      "states": [
        "Washington",
        "Oregon",
        "California"
      ]
    }
  }
}

是针对架构的有效 JSON 对象。 和

{
  "data": {
    "type": "myObject",
    "attributes": {
      "states": [
        "British Columbia",
        "Alberta",
        "Ontario"
      ]
    }
  }
}

对于架构也是一个有效的 JSON 对象

但是,

{
  "data": {
    "type": "myObject",
    "attributes": {
      "states": [
        "Washington",
        "Oregon",
        "Alberta"
      ]
    }
  }
}

不是针对架构的有效 JSON 对象。

我尝试了以下架构定义:

{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "properties": {
        "type": {
          "type": "string"
        },
        "attributes": {
          "type": "object",
          "properties": {
            "states": {
              "type": "array",
              "items": {
                "oneOf": [
                  {
                    "enum": ["Washington","Oregon","California"],
                    "description": "United States"
                  },
                  {
                    "enum": ["British Columbia","Alberta", "Ontario"],
                    "description": "Canada"
                  }
                ]
              },
              "description": "Filter by states"
            }
          }
        }
      }
    }
  }
}

但是对于上面的这个架构,这仍然被认为是有效的:

{
  "data": {
    "type": "myObject",
    "attributes": {
      "states": [
        "Washington",
        "Oregon",
        "Alberta"
      ]
    }
  }
}

顺便说一句,您可以使用它来测试 JSON 对象是否符合架构:https://www.jsonschemavalidator.net/

谢谢!

【问题讨论】:

    标签: jsonschema openapi


    【解决方案1】:

    您需要颠倒 oneOf 和 items 关键字的顺序,以便对所有项目使用相同的 oneOf 子句:

    ...
                "states": {
                  "type": "array",
                  "oneOf": [
                    {
                      "items": {
                        "enum": ["Washington","Oregon","California"],
                        "description": "United States"
                      }
                    },
                    {
                      "items": {
                        "enum": ["British Columbia","Alberta", "Ontario"],
                        "description": "Canada"
                      }
                    }
                  ]
                },
    ...
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-04
      • 2022-12-17
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      • 2018-03-20
      相关资源
      最近更新 更多