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文件中的错误在哪里?

推荐答案

我发现,在内置json模块模糊不清的许多情况下,simplejson模块提供了更多描述性错误.例如,对于列表中最后一项后面有逗号的情况:

json.loads('[1,2,]')
....
ValueError: No JSON object could be decoded

这不是很好的描述.与simplejson相同的操作:

simplejson.loads('[1,2,]')
...
simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 5 (char 5)

Much better! Likewise for other common errors like capitalizing True.

Json相关问答推荐

使用Jolt变换转换JsonArray以将关键字转移到内部JsonArray中

您可以使用Jolt对JSON执行OR条件吗

JSON:将项';S键/名称移动到属性中,并使用JQ将其转换为数组

Jolt-在数组列表中插入新的字段

NoneType 对象的 Python 类型错误

如何使用 JOLT 使用输入数组中的值和层次 struct 中的其他字段创建数组

将不带正文的 CURL POST 转换为 RESTRequest Delphi 代码 / 为 Dropbox API /get_current_account 端点编写 Delphi 代码

jq :遍历 json 并在键存在时检索集合

使用 ConvertFrom-Json 后,Powershell 访问 JSON 中的嵌套对象

坚持弄清楚如何使用 api 响应来调用以从不同的链接检索响应

将文本转换为 python 列表

Go - JSON 验证抛出错误,除非我在 struct 中使用指针.为什么?

使用 json 值过滤 Django 模型

如何用 Xidel 正确读取这个 JSON 文件?

.NET 对象最灵活的序列化是什么,但实现起来很简单?

如何使用 C# 将 JSON 文本转换为对象

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

在浏览器中查看 JSON 文件

如何从 github API 解析链接头

如何在 postgresql 9.3 中循环 JSON 数组