获取每个jsonschema错误的属性 [英] Get the property for each jsonschema errror

查看:587
本文介绍了获取每个jsonschema错误的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定哪个属性导致了错误.对于每种类型的错误,获取属性的方式似乎都不同.

I am trying to determine which property caused the error. It seems for each type of error the way to get the property is different.

from jsonschema import Draft4Validator

request_json = {
  'num_pages': 'invalid',
  'duration': 'invalid',
  'dne': 'invalid'
}

schema = {
  "patch": {
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "location": {},
      "description": {},
      "objectives": {},
      "num_pages": {"type": "integer"},
      "duration": {"type": "integer"}
    },
    "required": ["name"],
    "additionalProperties": False
  }
}

v = Draft4Validator(schema['patch'])
errors = []

for error in v.iter_errors(request_json):
    print error.__dict__

在此示例中,我想使用字段和错误构造输出.

From this example I would like to construct output with the field and error.

{
  num_pages: 'invalid is not an integer',
  duration: 'invalid is not an integer',
  'dne': 'unexpected additional property',
  'name': 'property is required'
}

目前我有以下内容

    if error.relative_schema_path[0] == 'required':
        errors.append({error.message.split(' ')[0]: 'Required property'})
    elif error.relative_path:
        # field: error_message
        errors.append({error.relative_path[0]: error.message})
    # Additional Field was found
    else:
        errors.append({error.instance.keys()[0]: error.message})

如果存在多个错误,则不能保证error.instance.keys()[0]是正确的.

If there are multiple errors then error.instance.keys()[0] is not guaranteed to be correct.

推荐答案

推荐的方法遍历和处理错误是使用ErrorTree对象.

The recommended approach to traverse and process errors is to use an ErrorTree object.

tree = ErrorTree(v.iter_errors(instance))

从这里您可以获取实例的全局错误:

From here you can get global errors to the instance:

tree.errors

数组中第一项的错误:

if 1 in tree:
    tree[1].errors

这篇关于获取每个jsonschema错误的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆