获取属性foreach json架构错误

时间:2014-12-11 18:03:30

标签: python json python-2.7 jsonschema

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

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__

从这个例子中我想用字段和错误构造输出。

{
  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]无效。

1 个答案:

答案 0 :(得分:0)

recommended approach to traverse and process errors是使用ErrorTree对象。

tree = ErrorTree(v.iter_errors(instance))

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

tree.errors

数组中第一项的错误:

if 1 in tree:
    tree[1].errors