import jsonschema
from jsonschema import validate, draft7_format_checker
from jsonschema.exceptions import SchemaError, ValidationError
schema = {
"title": "validate_融资信息数据结构",
"description": "validate_融资信息数据结构",
"type": "object",
"properties": {
"one": {
"type": "string",
"maxLength": 70,
"minLength": 2,
"not": {
"enum":["\\N"]
}
}
}
}
data = {
'one':123,
'two': '',
'three': '',
"companyNameEngD7esc":""
}
results = {
}
try:
a = validate(instance=data, schema=schema, format_checker=draft7_format_checker)
print(a)
except SchemaError as e:
err_arr = 'site:%s' % "--> ".join([i for i in e.path])
err_info = 'info:%s' % e.message
results['schema'] = [err_arr, err_info]
hint = "False&%s" % results
print(hint)
except ValidationError as e:
validator = jsonschema.Draft6Validator(schema)
errors = validator.iter_errors(data) # jsondata验证
for error in errors:
key = str(error).split('On instance')[1].replace('\n', '').split('\']')[0].replace('[\'', '')
value = str(error).split('\n')[0]
results[key] = value
hint = "False&%s" % results
print(hint,type(hint))
第二个版本
from jsonschema import validate, ValidationError
schema = {
"title": "validate_融资信息数据结构",
"description": "validate_融资信息数据结构",
"type": "object",
"properties": {
"one": {
"type": "string",
"maxLength": 70,
"minLength": 2,
"not": {
"enum":["\\N"]
}
}
}
}
data = {
'one':123,
'two': '',
'three': '',
"companyNameEngD7esc":""
}
try:
validate(instance=data, schema=schema)
print("检验通过")
except ValidationError as e:
print("校验失败")
for error in e.absolute_schema_path:
print(f"Field: {
error} - Reason: {
e.message}")