Python 代码从一些长的复杂的 JSON 文件中加载数据:
with open(filename, "r") as f:
data = json.loads(f.read())
(注意: 最佳代码版本应该是:
with open(filename, "r") as f:
data = json.load(f)
但两者表现出相似的行为)
对于许多类型的 JSON 错误(缺少分隔符、字符串中不正确的反斜杠等) ,这将打印出一个非常有用的消息,其中包含发现 JSON 错误的行号和列号。
然而,对于其他类型的 JSON 错误(包括经典的“在列表中的最后一项使用逗号”,以及大写 true/false 等其他错误) ,Python 的输出只是:
Traceback (most recent call last):
File "myfile.py", line 8, in myfunction
config = json.loads(f.read())
File "c:\python27\lib\json\__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "c:\python27\lib\json\decoder.py", line 360, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "c:\python27\lib\json\decoder.py", line 378, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
对于这种类型的 ValueError,如何让 Python 告诉您 JSON 文件中的错误位置?