我正在尝试用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)
。。。谢谢你的帮助
json1 = json.loads(jsonfile)
行引发JSONDecodeError
异常,但该行不在try
块中。你知道吗您可以看到,正是这一行在回溯中引发了异常:
保护
json.loads()
,或者给它自己的try...except
:或者将行放在环绕
for
循环的try
中:请注意,项访问(订阅)可以抛出
KeyError
、IndexError
或TypeError
异常,这取决于应用[...]
的对象类型,并且不需要使用.keys()
来迭代字典的键。接下来,因为您只对dictionary值感兴趣,所以您应该真正地迭代.values()
,以使代码更具可读性。你知道吗以下是处理错误JSON数据的更完整的方法:
相关问题 更多 >
编程相关推荐