jsonSchema进行日志格式校验
jsonSchema
功能
1、属性校验
2、属性类型校验
3、属性值校验
下载
pip3 install jsonschema
import jsonschema
from jsonschema import validate, draft7_format_checker
from jsonschema.exceptions import SchemaError, ValidationError
from jsonschema.validators import validator_for, Draft7Validator, Draft3Validator
my_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "TestInfo",
"description": "some information about test",
"type": "object",
"properties": {
"name": {
"description": "Name of the test"
,"type": "object"
,"properties": {
"first_name":{
"description": "Name of the test",
"type": "string"
},
"last_name":{
"description": "Name of the test",
"type": "string"
}
}
,"required":['str']
},
"age": {
"description": "age of test",
"type": "integer",
"minimum": 0,
"maximum": 120
},
"pet": {
"enum": ["dog", "cat"]
}
},
"required": [
"name", "age", "pet"
]
}
json_data1 = {
"name": {"str":'bbbbb'},
"age": 25,
"pet": "cat"
}
json_data2 = {
"name": {"str1":'bbbbb'},
"age": 25,
"pet": "cat"
}
json_data3 = {
"name": {"str":'bbbbb'},
"age": 25,
"pet": "cat1"
}
json_data4 = {
"name": {"str":'bbbbb'},
"age": -1,
"pet": "cat"
}
json_data5 = {
"name": {"first_name": 1, "last_name": 2},
"age": 121,
"pet": "cat1"
}
def json_check1(data,schema):
try:
validate(instance=data, schema=schema, format_checker=draft7_format_checker)
except SchemaError as e:
return 1, "验证模式schema出错,出错位置:{},提示信息:{}".format(" --> ".join([i for i in e.path if i]), e.message)
except ValidationError as e:
return 2,"不符合schema规定,出错字段:{},提示信息:{}".format(" --> ".join([i for i in e.path if i]), e.message)
else:
return 0,'success'
def json_check2(data,schema):
v = Draft3Validator(schema)
for error in sorted(v.iter_errors(data), key=str):
res = "验证模式schema出错,出错位置:{},提示信息:{}".format(" --> ".join([i for i in error.path if i]), error.message)
print(res)
# print(json_check1(json_data1,my_schema))
#
# print(json_check1(json_data2,my_schema))
#
# print(json_check1(json_data3,my_schema))
#
# print(json_check1(json_data4,my_schema))
#
# print(json_check1(json_data5,my_schema))
json_check2(json_data5, my_schema)