与“无法解码JSON对象"相比,显示更好的错误消息. [英] Displaying better error message than "No JSON object could be decoded"
问题描述
Python代码从一些复杂的JSON长文件中加载数据:
Python code to load data from some long complicated JSON file:
with open(filename, "r") as f:
data = json.loads(f.read())
(注意:最佳代码版本应为:
(note: the best code version should be:
with open(filename, "r") as f:
data = json.load(f)
但都表现出相似的行为)
but both exhibit similar behavior)
对于许多类型的JSON错误(缺少分隔符,字符串中的反斜杠不正确等),这会打印出一条非常有用的消息,其中包含找到JSON错误的行号和列号.
For many types of JSON error (missing delimiters, incorrect backslashes in strings, etc), this prints a nice helpful message containing the line and column number where the JSON error was found.
但是,对于其他类型的JSON错误(包括经典的在列表中的最后一项上使用逗号",以及诸如大写的true/false等其他内容),Python的输出仅为:
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文件中的错误在哪里?
For that type of ValueError, how do you get Python to tell you where is the error in the JSON file?
推荐答案
我发现,在内置json
模块含糊不清的许多情况下,simplejson
模块给出了更多的描述性错误.例如,对于列表中最后一个项目后面有逗号的情况:
I've found that the simplejson
module gives more descriptive errors in many cases where the built-in json
module is vague. For instance, for the case of having a comma after the last item in a list:
json.loads('[1,2,]')
....
ValueError: No JSON object could be decoded
这不是很描述. simplejson
的相同操作:
which is not very descriptive. The same operation with simplejson
:
simplejson.loads('[1,2,]')
...
simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 5 (char 5)
好多了!同样,对于其他常见错误,例如将True
大写.
Much better! Likewise for other common errors like capitalizing True
.
这篇关于与“无法解码JSON对象"相比,显示更好的错误消息.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!