轶哥

📚 Having fun with AI Agent. Always learning.

Json Schema定义“既可以是对象,又可以是数组”
  •   更新:2021-02-06 23:46:41
  •   首发:2021-02-06 23:45:04
  •   教程
  •   2426

如果我想定义json的内容(root)既可以是一个对象,又可以是一个数组,应该如何书写json schema?

这个问题换一种描述方式,“json schema定义了一个对象,但是希望内容也可以是这个对象的数组,如何书写json schema?”。

例如,Typescript中:root: object | [object]

例如,我希望数据可以是下面这样的一个对象:

{
  "method": "GET"
}

也可以是这样的数组:

[
  {
    "method": "GET"
  }
]

根据https://json-schema.org/公开的Json Schema草案,可以这样来实现:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": [
    "array",
    "object"
  ],
  "items": {
    "$ref": "#"
  },
  "properties": {
    "method": {
      "type": "string",
      "enum": [
        "GET",
        "POST",
        "PUT",
        "DELETE",
        "OPTIONS",
        "PATCH",
        "HEAD"
      ]
    }
  }
}

这样的写法就可以兼容以上两种情况了。其中$ref的值为#,代表引用自身。

如果希望method即可以是一个string类型的枚举类型,也可以是包含上述定义的数组。可以这样编写:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": [
    "array",
    "object"
  ],
  "items": {
    "$ref": "#"
  },
  "definitions": {
    "method": {
      "type": "string",
      "title": "请求方法",
      "description": "支持的 HTTP 请求方法。目前支持 'DELETE'、'GET'、'HEAD'、'PATCH'、'POST'、'PUT' 以及 'OPTIONS'。它还可以是一个 HTTP 方法的数组。",
      "default": "GET",
      "enum": [
        "GET",
        "POST",
        "PUT",
        "DELETE",
        "OPTIONS",
        "PATCH",
        "HEAD"
      ]
    }
  },
  "properties": {
    "method": {
      "anyOf": [
        {
          "$ref": "#/definitions/method"
        },
        {
          "type": "array",
          "items": {
            "$ref": "#/definitions/method"
          }
        }
      ]
    }
  }
}

这样一来,自动补全提示如下:

jsonschema.png

因此,

[
  {
    "method": [
      "GET",
      "PUT"
    ]
  }
]

[
  {
    "method": "POST"
  }
]

都是合法的。

打赏
交流区

暂无内容

尚未登陆
发布
  上一篇 (Linux配置Swap)
下一篇 (win10链路聚合,双网卡带宽叠加负载均衡)  

评论回复提醒