[英]Show all errors in json schema using json validate using 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")
您可以添加continue
或pass
except塊,以使其在第一個異常發生后退出退出。
要在單個實例中獲取所有驗證錯誤,請使用驗證器類的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()方法通過啟發式方法選擇最佳匹配錯誤,並將其提高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.