首页 > 解决方案 > 使用 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")

标签: pythonjsonvalidation

解决方案


要在单个实例中获取所有验证错误,请使用验证器类的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 ()方法通过一些启发式方法在这些错误中选择最佳匹配错误并引发它。


推荐阅读