JsonSchema
JsonSchemea,也叫Json模式,是一个用于描述和验证JSON数据的强力工具;其有多种用途,其中之一就是示例验证。验证可以是交互式或非交互式的,例如:应用程序可以使用JSON模式来构建用户界面,进行用户数据检查或验证各种来源的数据(来源:百度百科)。
应用
比如我们想上传一个景点推荐指南,并限制上传的内容,我们就可以json来存储,如下所示:
{
"city":"南京",
"age":2500,
"scenicSpots":[
{
"name":"德基广场",
"reason":"体验800w厕所",
"list":["1200w厕所","800w厕所"]
}
]
}
为此我们需要制定JSON Schema,来作为我们上传的规则,JsonSchema也是Json串。
Object
首先,外部是一个大的Json串,包含了"city","age","scenicSpots"字段,所以我们可以先写好外部的规则 :
{
"type":"object",
"properties":{},
"required":["city","age","scenicSpots"]
}
其中"type"表示接下来我们要制定规则的对象的类型,是object,"properties"是用来描述这个对象中所有的键的属性;"required"表示这个对象中必含的键,缺少其中的任何一个都会提示错误。
字符串与数据类型
"name"与"age"是基本的数据类型,用type描述其类型即可。
"city":{
"type":"string"
},
"age":{
"type":"number"
}
数组
scenicSpots是一个数组,里面存放Object对象。
"scenicSpots":{
"type":"array",
"items":{
}
}
其中"type"表示接下来我们要制定规则的对象的类型,是array;items是这个数组的元素,有两种方式来验证值:列表验证和元祖验证:
- 列表验证(List validation):任意长度的数组,数组中每个值都匹配相同的 Schema;
- 元组验证(Tuple validation):固定长度的数组,数组中每个值可以匹配不同的 Schema;
列表验证(List validation):
使用items设置单个模式,数组内的所有类型相同;
{
"type": "array",
"items": {
"type": "number"
}
}
使用contains匹配数组内的某一个或多个类型;
{
"type": "array",
"contains": {
"type": "number"
}
}
元组验证(Tuple validation),以下规则匹配:["我爱工作(失智)",100]
{
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "number"
}
]
}
这样我们就制定了一个简单的Json规则。JsonSchema中包含了更多的属性,如:枚举类型,正则表达式,注释等等,可以看这篇大佬的博客:JSON schema(模式)-CSDN博客;
{
"type": "object",
"properties": {
"city": { "type":"string" },
"age": { "type":"number" },
"scenicSpots": {
"type": "array",
"items": {
"type":"object",
"properties": {
"name": { "type":"string" },
"reason": { "type":"string" },
"list": {
"type": "array",
"items": { "type":"string" }
}
},
"required": ["name","reason","list"]
}
}
},
"required": ["city","age","scenicSpots"]
}