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

推荐订阅源

The GitHub Blog
The GitHub Blog
S
SegmentFault 最新的问题
MyScale Blog
MyScale Blog
有赞技术团队
有赞技术团队
V
Visual Studio Blog
T
The Blog of Author Tim Ferriss
爱范儿
爱范儿
Vercel News
Vercel News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
D
DataBreaches.Net
美团技术团队
Microsoft Security Blog
Microsoft Security Blog
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
A
About on SuperTechFans
云风的 BLOG
云风的 BLOG
The Cloudflare Blog
宝玉的分享
宝玉的分享
V
V2EX
Microsoft Azure Blog
Microsoft Azure 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
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"
  }
]

都是合法的。