使用 json 验证使用 python 显示 json 模式中的所有错误

Ana*_*idu 7 python validation json

我正在编写一个 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")
Run Code Online (Sandbox Code Playgroud)

Nit*_*tty 7

要在单个实例中获取所有验证错误,请使用验证器类的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('------')
Run Code Online (Sandbox Code Playgroud)

输出:

'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

------
Run Code Online (Sandbox Code Playgroud)

该jsonschema.validate()方法,通过启发式选择其中的最佳匹配误差,提高了它。


小智 0

您可以在 except 块中添加continue或 ,pass以在第一个异常后跳过退出。