Python code to load data from some long complicated JSON file:
with open(filename, "r") as f:
data = json.loads(f.read())
(注:最佳代码版本应为:
with open(filename, "r") as f:
data = json.load(f)
但两者表现出相似的行为)
对于许多类型的JSON错误(缺少分隔符、字符串中的反斜杠不正确等),这将打印一条很有帮助的消息,其中包含发现JSON错误的行号和列号.
However, for other types of JSON error (including the classic "using comma on the last item in a list", but also other things like capitalising true/false), Python's output is just:
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文件中的错误在哪里?