python - 获取每个 json 模式错误的属性

标签 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] 是正确的。

最佳答案

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

tree = ErrorTree(v.iter_errors(instance))

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

tree.errors

数组中第一项的错误:

if 1 in tree:
    tree[1].errors

关于python - 获取每个 json 模式错误的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27429462/

相关文章:

python - 如何使用 PYTHON 遍历目录中的文件并将 INFO 插入 MySQL 数据库

javascript - 如何在 javascript 中解析 JSON 数组,该数组中的每个对象都有单引号?

Python在JSON结构中获取 sibling

json - VBA-JSON : Add entry to Existing File

python - 枚举可以用在递归中吗?这个例子的递归是什么?

python - 在Python中使某个语句永远循环

python - "The indices parameter is deprecated and will be removed (assumed True) in 0.17"是什么意思?

python - Kivy TextInput后台问题

python - MongoDB 中 GB 数据的数据摄取

php - Mako 中使用 Pylons 的条件运算符