看着官方文档 https://json-schema.org/understanding-json-schema/ 做了点笔记
JSON Schema 是一种描述 JSON 数据结构的声明格式,可用于验证 JSON 数据的合法性的强大工具。其本身也是通过 JSON 来编写的。
首先用 “$schema” 描述使用的版本,用”title”简单描述这个 json schema 用于描述的内容
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"title":"test"
}
1、type
type 关键字是 JSON Schema 的基础, 它指定数据类型。 JSON Schema 定义了如下基础数据类型:
- string
- number
- integer
- object
- array
- boolean
- null
示例:
{"type": "string"}
表示数据类型只能是字符串
{ "type": ["number", "string"] }
表示数据类型可以是数字或者字符串
2、string
string 类型用于指定字符串文本,可以使用关键字 minLength 和 maxLength 来限定字符串的最小和最大长度(都需是非负整数)。
{
"type": "string",
"minLength":2,
"maxLength":3
}
ps:学习的过程中可以同步使用文末提到的辅助工具。
还可以用正则表达式
{
"type": "string",
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}
对于一些常用的字符串格式,json schema 可以通过关键字 format 来指定对应的格式,如下
{
"type":"string",
"format":"email"
}
内置的格式有日期和时间、电子邮箱地址、主机名、IP地址等。
3、数字类型
{ "type": "integer" }
只能用于表示整数
{ "type": "number" }
可以表示整数和浮点数
{
"type": "number",
"multipleOf" : 10
}
multipleOf 表示数值需是给定数字的倍数,它可以设置为任何正数
可以使用如下关键字指定数值范围
x ≥ minimum
× > exclusiveMinimum
x ≤ maximum
x < exclusiveMaximum
{
"type": "number",
"minimum": 0,
"exclusiveMaximum": 100
}
4、object 类型
object 类型理解就是将一组变量的属性合在一个对象里进行描述,通过关键字 properties 来描述,如下:
{
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength":2,
"maxLength":20
},
"age": {
"type": "integer"
}
}
}
关键字 additionalProperties 用于描述额外属性
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
}
},
"additionalProperties": false
}
表示除了前面描述的键值对,没有额外的属性增加,
或者可以限制额外新增的需要满足特定类型
"additionalProperties": { "type": "string" }
required 表示一定要带的属性字段
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
},
"required":["name"]
}
minProperties 和 maxProperties关键字来限制对象的属性数量,需为非负整数
{
"type": "object",
"minProperties": 2,
"maxProperties": 3
}
5、数组
{
"type": "array",
"items": {
"type": "number"
}
}
关键字 items 可以限制数组每个元素类型
{
"type":"array",
"items":[
{"type":"string"},
{"type":"number"},
{"type":"string"},
{"type":"number"},
]
}
也可以像上面这样限制数组元素依次的类型,如果不希望后面还有元素,可以使用 false 表示
{
"type":"array",
"items":[
{"type":"string"},
false
]
}
contains 只需要针对数组中的一个或多个元素进行验证
{
"type": "array",
"contains": {
"type": "number"
},
"minContains": 2,
"maxContains": 3
}
可以使用 minItems 和 maxItems 关键字指定数组的长度,需是非负数
{
"type": "array",
"minItems": 2,
"maxItems": 3
}
如果希望数组中的每个元素都是唯一的。只需将 uniqueItems 关键字设置为true.
{
"type": "array",
"uniqueItems": true
}
6、bool 类型
{"type": "boolean"}
其值只能是 true 和 false
7、枚举值
{
"type":"object",
"properties":{
"colour": {
"enum": ["red", "yellow", "green"]
}
}
}
8、const
{
"properties": {
"country": {
"const": "china"
}
}
}
const 用于限定字段只能是单个值
9、属性依赖
{
"type":"object",
"properties":{
"test":{
"type":"string"
},
"name": {
"type":"string",
},
"passwd":{
"type":"string",
}
},
"required":["test"],
"dependentRequired":{
"name":["passwd"]
}
}
比如这里name并不是必须属性,但如果提供了,则一定需要同步提供passwd。
辅助工具
1、json schema 校验 https://www.jsonschemavalidator.net/
2、在线生成 json schema 工具 https://extendsclass.com/json-schema-validator.html