jsonschema模块
jsonschema是一个超强的python库。
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于数据传输和配置文件。为了确保JSON数据的有效性和一致性,需要使用JSON Schema来定义数据结构和验证规则。
JSON Schema是一种用于描述JSON数据结构和验证规则的语言。它可以定义JSON数据的期望结构、数据类型、最小和最大值等规则,并用于验证输入数据是否符合这些规则。
要使用python jsonschema 需要先安装它,可以使用pip来安装
pip install jsonschema
首先,需要定义一个JSON Schema,以描述JSON数据的结构和验证规则。JSON Schema通常以JSON格式表示
{ "type": "object", "required": ["code", "success","email"],//required 表示字段必须存在,不存在则报错 "properties": { "code": {"type":"integer"}, "success": {"type":"boolean"}, "msg": {"type":"string"}, "data":{ "type": "array", "items": { "type": "object", "properties":{ "name": {"type": "string"}, "age": {"type": "integer"}, "sex": {"type": "string", "enum": [0,1]},//enum表示枚举 "money":{"type": "number","minimum": 100,"maximum": 99999,"multipleOf": 2},//最小值,>= 100,最大值,<=9999,值必须是2的整数倍 "distance": {"type": "number","exclusiveMinimum": 100,"exclusiveMaximum": 99999},//最小值,>100,最大值,<99999 "remark": {"type": "string","minLength": 4 ,"maxLength": 200 },//字符串最小长度4,最大长度200 "email": {"type": "string" , "pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"},//使用正则表达式校验 "time" :{"type" : ["string","null"]}//表示该字段允许多种类型 } } } } }
验证json数据,以下是一个示例:
import json import jsonschema
//定义的jsonschema schema = { "type": "object", "required": ["code", "success","email"], "properties": { "code": {"type":"integer"}, "success": {"type":"boolean"}, "msg": {"type":"string"}, "data":{ "type": "array", "items": { "type": "object", "properties":{ "name": {"type": "string"}, "age": {"type": "integer"}, "sex": {"type": "string", "enum": [0,1]}, "money":{"type": "number","minimum": 100,"maximum": 99999,"multipleOf": 2}, "distance": {"type": "number","exclusiveMinimum": 100,"exclusiveMaximum": 99999}, "remark": {"type": "string","minLength": 4 ,"maxLength": 200 }, "email": {"type": "string" ,"minLength": 4 ,"maxLength": 30, "pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"}, "time" :{"type" : ["string","null"]} } } } } } //待验证的json数据
data = {
"code": 0,
"success": True,
"msg" : "请求成功",
"data": [{
"name": "John Doe",
"age": "asdsad",
"email": "123"
}]
}
try: jsonschema.validate(instance = data,schema=schema)
print("校验通过")
except jsonschema.exceptions.ValidationError as e:
print("校验未通过,错误信息",e)
使用validate
函数来验证JSON数据是否符合给定的JSON Schema。如果JSON数据有效,则不会引发异常;否则,将引发jsonschema.exceptions.ValidationError
异常,并提供有关验证失败的详细信息。