我正在编写一个 Python 代码来验证 JSON 模式,但它没有显示其中的所有错误,仅显示第一个错误。任何人都可以帮助修复代码以显示所有错误。
下面是代码:
from __future__ import print_function
import sys
import json
import jsonschema
from jsonschema import validate
schema = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
},
}
data = \
[
{ "name": 20, "price": 10},
]
print("Validating the input data using jsonschema:")
for idx, item in enumerate(data):
try:
validate(item, schema)
sys.stdout.write("Record #{}: OK\n".format(idx))
except jsonschema.exceptions.ValidationError as ve:
sys.stderr.write("Record #{}: ERROR\n".format(idx))
sys.stderr.write(str(ve) + "\n")
最佳答案
要在单个实例中获取所有验证错误,请使用 iter_errors()验证器类的方法。
例如。:
import jsonschema
schema = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
},
}
data = { "name": 20, "price": "ten"}
validator = jsonschema.Draft7Validator(schema)
errors = validator.iter_errors(data) # get all validation errors
for error in errors:
print(error)
print('------')
输出:
'ten' is not of type 'number'
Failed validating 'type' in schema['properties']['price']:
{'type': 'number'}
On instance['price']:
'ten'
------
20 is not of type 'string'
Failed validating 'type' in schema['properties']['name']:
{'type': 'string'}
On instance['name']:
20
------
jsonschema.validate()方法通过一些启发式方法在这些错误中选择最佳匹配错误并提出它。
关于python - 使用 json 验证使用 python 显示 json 模式中的所有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52196407/