JSON Schema指的是数据交换中的一种虚拟的“合同”。
JSON验证器负责验证语法错误,JSON Schema负责提供一致性检验。
JSON Schema是数据接收方额第一道防线,也是数据发送方节约时间、保证数据正确的好工具。
JSON Schema可以解决下列有关一致性验证的问题。
1、 值的数据类型是否正确:可以具体规定一个值是数字、字符串等类型;
2、 是否包含所需的数据:可以规定哪些数据是需要的,哪些是不需要的;
3、 值的形式是不是我需要的:可以指定范围、最小值和最大值。
编写JSON Schema的步骤:
一、在JSON第一个名称——值对中,声明其为一个schema文件。声明的名称必须为”$schema”,值必须为所用草拟版本的连接:
{
"$schema": "http://json-schema.org/draft-04/schema#",
}
二、第二个名称——值对是JSON Schema文件格式,比如表示一只猫:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title":"cat"
}
三、定义title的相关属性值:
"properties":{
"name":{
"type":"string"
},
"age":{
"type":"number",
"description":"Your cat's age in years"
},
"declawed":{
"type":"boolean"
},
"description":{
"type":"string"
}
}
四、完整的Json Schema代码如下:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title":"cat",
"properties":{
"name":{
"type":"string"
},
"age":{
"type":"number",
"description":"Your cat's age in years"
},
"declawed":{
"type":"boolean"
},
"description":{
"type":"string"
}
},
"required":[
"name",
"age",
"declawed"
]
}
完整的案例:
1、验证猫的完整JSON代码
{
"name":"TOM",
"age":2,
"declawed":false,
"description":"TOM loves to sleep all day."
}
其中required定义的是必填字段。
在线测试网址:
http://www.jsonschemavalidator.net/
本文参考JSON必知必会编写。