Python中如何获取jsonschema的全部ValidationError验证错误?
获取JSON Schema验证的所有错误
默认的validate函数会在遇到第一个验证错误时就抛出异常,要获取全部错误,需要使用jsonschema库的验证器迭代器方法iter_errors,它会遍历所有不符合Schema规则的错误点。
修改后的代码示例
from jsonschema import validate, ValidationError from jsonschema.validators import Draft202012Validator # 根据你的Schema版本选择对应验证器 def validate_schema(instance, schema): errors = [] # 实例化验证器 validator = Draft202012Validator(schema) # 遍历所有验证错误 for error in validator.iter_errors(instance): errors.append(f"错误路径: {' -> '.join(map(str, error.path))}, 错误信息: {error.message}") if not errors: print("JSON已通过验证。") else: print("验证错误列表:") for err_msg in errors: print(f"- {err_msg}") json_schema = { "type": "object", "properties": { "product name": {"type": "boolean"}, "category_id": {"type": "number"}, "model_year": {"type": "number"}, "list_price": {"type": "number"}, "brand_id": {"type": "number"} } } data = { "product_name": 123, "category_id": 8, "model_year": '2022', "list_price": '1495', "brand_id": '11' } validate_schema(data, json_schema)
关键说明
- 选择对应版本的验证器:比如你的Schema如果是Draft 7,就用
Draft7Validator,确保和Schema版本匹配。 iter_errors会返回所有验证错误的迭代器,每个错误对象包含path(错误字段的路径)和message(错误描述)等信息,方便定位问题。- 额外注意:你的代码里存在函数名不匹配(定义
validate_schema却调用schema_validator)、Schema字段product name和数据字段product_name名称不一致的问题,这些也会被检测为错误。
内容的提问来源于stack exchange,提问作者Ammar Fasih Hanif
相关产品推荐
相关产品推荐

