为什么未捕获此json.decoder.JSONDecodeError

时间:2018-11-17 16:53:23

标签: python json

我正在尝试使用python3.5解析jsonfile的负载,其中许多不具有某些预期的元素。错误/例外json.decoder.JSONDecodeError是绝对预期的。但是,我试图对此做出反应,但未以某种方式捕获该错误:

代码

    #/usr/bin/python3

import pymongo
import pprint
import json
import sys

jsonfile = open(sys.argv[1],'r').read()
json1 = json.loads(jsonfile)


try:
        for key1 in json1["result"]["malware"].keys():
                print("Malware: " + json1["result"]["malware"][key1]["malware"])
                print("File: " + json1["result"]["malware"][key1]["file"])
except AttributeError:
        print("We'll handle that")
except json.decoder.JSONDecodeError:
        print("We'll handle that too")

我仍然得到...

Traceback (most recent call last):
  File "pyjson.py", line 9, in <module>
    json1 = json.loads(jsonfile)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

...感谢您的帮助

1 个答案:

答案 0 :(得分:1)

json1 = json.loads(jsonfile)行引发JSONDecodeError异常,但该行不在try块中。

您可以看到正是该行在回溯中引发了异常:

Traceback (most recent call last):
  File "pyjson.py", line 9, in <module>
    json1 = json.loads(jsonfile)
  # ...

保护json.loads(),方法是提供自己的try...except

try:
    json1 = json.loads(jsonfile)
except json.decoder.JSONDecodeError:
    print("We'll handle that")
else:
    try:
        for key1 in json1["result"]["malware"].keys():
            print("Malware: " + json1["result"]["malware"][key1]["malware"])
            print("File: " + json1["result"]["malware"][key1]["file"])
    except AttributeError:
        print("We'll handle that too")

或通过将行放在try循环周围的for内:

try:
    json1 = json.loads(jsonfile)
    for key1 in json1["result"]["malware"].keys():
        print("Malware: " + json1["result"]["malware"][key1]["malware"])
        print("File: " + json1["result"]["malware"][key1]["file"])
except AttributeError:
    print("We'll handle that")
except json.decoder.JSONDecodeError:
    print("We'll handle that too")

请注意,项访问(订阅)可能会抛出KeyErrorIndexErrorTypeError异常,具体取决于{{1 }}被应用,并且您不需要使用[...]遍历字典的键。接下来,由于您只对字典 values 感兴趣,因此您应该真正遍历.keys()以使代码更具可读性。

以下是处理不良JSON数据的更完整方法:

.values()