惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
爱范儿
爱范儿
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
IT之家
IT之家
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
G
Google Developers Blog
V
V2EX
雷峰网
雷峰网
美团技术团队
博客园 - 【当耐特】
人人都是产品经理
人人都是产品经理
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
V
Visual Studio Blog
J
Java Code Geeks

轶哥博客

blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog blog
blog
2021-02-06 · via 轶哥博客

如果我想定义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"
  }
]

都是合法的。