1.JSON Schema的含义
JSON Schema 是用于验证 JSON 数据结构的强大工具,Schema可以理解为模式或者规则,可以理解为JSON中的正则表达式

2.语法

2.1 type
作用:约束数据类型
取值范围:integer,string,object,array,null,boolean,number
import jsonschema
# 准备校验规则
schema = {
"type": "object" # 注意 type 和 后面的 类型,都要放到 ”“ 中!
} #
准备数据
data = {"a": 1, "b": 2}
# 调用函数
res = jsonschema.validate(instance=data, schema=schema)
print(res)
2.2 properties
作用:是type:object关键字的辅助,用来检测object中每个属性是否满足条件,可以嵌套使用。
schema = {
"type": "object",
"properties": {
"success": {"type": "boolean"},
"code": {"type:": "integer"},
"message": {"type": "string"},
"money": {"type": "number"},
"address": {"type": "null"},
"data": {
"type": "object",
"properties": { # 对 data 的对象值,进一步进行校验
"name": {"type": "string"},
"age": {"type": "integer"},
"height": {"type": "number"}
}
},
"luckyNumber": {"type": "array"}
}
}
2.3 required
作用:校验对象中必须存在的key,如果不存在则会抛出异常,比如校验一个学生信息的JSON数据,这个数据中必须有name,age,id这三个字段,就可以使用required
data = {
"success": True,
"code": 10000,
"message": "操作成功",
"data": None,
}
schema = {
"type": "object",
"required": ["success", "code", "message", "data"]
}
#校验data是否符合schema,如果不符合则会抛出ValidationError
res = jsonschema.validate(instance=data, schema=schema)
2.4 const
作用:校验key是否是一某个值,比如 gender 要求为男,就可以使用const
data = {
"success": True,
"code": 10000,
"message": "操作成功",
"data": None,
}
schema = {
"type": "object",
"properties": {
"success": {"const": True},
"code": {"const": 10000},
"message": {"const": "操作成功"},
"data": {"const": None}
},
"required": ["success", "code", "message", "data"]
}
2.5 pattern
作用:校验字符串是否满足正则表达式
一些基础的正则表达式:

data = {
"message": "!jeklff37294操作成功43289hke",
"mobile": "15900000002"
}
schema = {
"type": "object",
"properties": {
"message": {"pattern": "操作成功"},
"mobile": {"pattern": "^[0-9]{11}$"}
}
}
3.具体实例
import jsonschema
data = {
"success": False,
"code": 10000,
"message": "xxx登录成功",
"data": {
"age": 20,
"name": "lily"
}
}
schema = {
"type": "object",
"properties": {
"success": {"type": "boolean"},
"code": {"type": "integer"},
"message": {"pattern": "登录成功$"},
"data": {
"type": "object",
"properties": {
"name": {"const": "lily"},
"age": {"const": 20}
},
"required": ["name", "age"]
}
},
"required": ["success", "code", "message", "data"]
} #
res = jsonschema.validate(instance=data, schema=schema)
validate方法没有返回值,如果校验通过res的值是None,如果不通过那么就会直接抛出ValidationError
623

被折叠的 条评论
为什么被折叠?



