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

标签 python json validation

我正在编写一个 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/

相关文章:

node.js - 为什么 Mongoose 不验证空文档?

jquery - "xxx-xxxxxxx-yy"的输入字段需要验证

python - FFmpeg 最小化内存使用或向 youtube-dl 添加超时

python - 用 python : How to set up the graph correctly? 切割的图

Python,支持unicode的最佳方法?

python - 如何在 Python 2 中正确编码向量化函数条目

javascript - 如何使用jquery获取json数据

javascript - JS无法解析带有unicode字符的JSON

javascript - express.index 发送 json 对象时出现问题

c# - 在属性中指定允许的枚举值