python - 使用 json 显示 json 模式中的所有错误 使用 python 验证
问题描述
我正在编写一个 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 ()方法通过一些启发式方法在这些错误中选择最佳匹配错误并引发它。
推荐阅读
- animation - Xamarin.Forms。如何制作动画幻灯片和淡入淡出以进行搜索?
- ms-access - 当 Access 离开一条记录并移至下一条记录时会触发什么事件?
- spring-integration - Spring Integration Java DSL:带有 HttpMethod.PATCH 的 Http.outboundGateway 不起作用
- ios - 从 AppCenter 内部构建的 iOS 要求注册设备
- kubernetes - 在 K8S 中访问应用程序的证书:
- python - 安装了 Flask,但得到“ImportError: No module named flask”。可能是什么原因?
- c# - SpecFlow如何测量每个步骤的持续时间?
- python - 使用 Virustotal 和 Python 提取应用程序哈希的分数
- xaml - 使用 OnPlatform 时,无法让标签在 ResourceDictionary 中工作的 FontSize
- c++ - 为 clang 强制执行 C++98/03