为什么会这样json.decoder.JSONDecodeError错误不是caugh

2024-05-14 03:57:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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)

。。。谢谢你的帮助


Tags: inpyimportjsonusrlinefileprint
1条回答
网友
1楼 · 发布于 2024-05-14 03:57:58

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")

或者将行放在环绕for循环的try中:

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异常,这取决于应用[...]的对象类型,并且不需要使用.keys()来迭代字典的键。接下来,因为您只对dictionary感兴趣,所以您应该真正地迭代.values(),以使代码更具可读性。你知道吗

以下是处理错误JSON数据的更完整的方法:

try:
    data = json.loads(jsonfile)
except json.decoder.JSONDecodeError as e:
    print("Malformed JSON data, can't decode", e)
else:
    try:
        for entry in data["result"]["malware"].values():
            print("Malware:", entry["malware"])
            print("File:", entry["file"])
    except (AttributeError, IndexError, TypeError, KeyError) as e
        print("Unexpected data structure from the JSON file", e)

相关问题 更多 >