Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取每个jsonschema错误的属性_Python_Json_Python 2.7_Jsonschema - Fatal编程技术网

Python 获取每个jsonschema错误的属性

Python 获取每个jsonschema错误的属性,python,json,python-2.7,jsonschema,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

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

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]正确。

方法是使用ErrorTree对象

tree = ErrorTree(v.iter_errors(instance))
从这里可以获取实例的全局错误:

tree.errors
数组中第一项的错误:

if 1 in tree:
    tree[1].errors

你是对的,ErrorTree是推荐的方法,但它没有回答这个问题。@BARJ,我认为问题是这个问题有点模棱两可。据我所知,访问验证中的每一个错误都有问题,因此他可以用这些错误构建消息。我提供了这样一种手段。你认为问题是什么?啊,对。这个问题有点模棱两可。我认为他的意思是,给定一个验证错误,是什么属性导致了这个错误。例如,如果有类型错误,可以使用
schema\u路径
查找相应的属性。但是,如果您有一个必需的验证错误,那么要追溯导致错误的属性就不是那么简单了。这个问题是在他的第一句话中提出来的,这就是ErrorTree的目的。树中的每个错误都解释了图形的哪个部分出错。在提供的链接中有一些示例。