首页 > 解决方案 > JSON解码错误;从 Python 解析时 /escape 无效

问题描述

运行我的对象检测模型后,它会输出一个带有结果的 .json 文件。为了在我的 python 中实际使用模型的结果,我需要解析 .json 文件,但我没有尝试任何方法来实现它。我试图打开然后打印结果,但我得到了错误:

json.decoder.JSONDecodeError: Invalid \escape: line 4 column 41 (char 60)

如果您知道我做错了什么,我们将非常感谢您的帮助。我的代码:

with open(r'C:\Yolo_v4\darknet\build\darknet\x64\result.json') as result:
    data = json.load(result)
    result.close()

print(data)

我的 .json 文件

[
{
 "frame_id":1, 
 "filename":"C:\Yolo_v4\darknet\build\darknet\x64\f047.png", 
 "objects": [ 
  {"class_id":32, "name":"right", "relative_coordinates":{"center_x":0.831927, "center_y":0.202225, "width":0.418463, "height":0.034752}, "confidence":0.976091}, 
  {"class_id":19, "name":"h", "relative_coordinates":{"center_x":0.014761, "center_y":0.873551, "width":0.041723, "height":0.070544}, "confidence":0.484339}, 
  {"class_id":24, "name":"left", "relative_coordinates":{"center_x":0.285694, "center_y":0.200752, "width":0.619584, "height":0.032149}, "confidence":0.646595}, 
 ] 
}
]

(还有几个检测到的对象,但不包括它们)

标签: pythonarraysjson

解决方案


其他响应者当然是对的。这不是有效的 JSON。但有时您无法选择更改格式,例如因为您正在处理损坏的数据转储,其中原始源不再可用。

解决这个问题的唯一方法是以某种方式对其进行消毒。这当然不理想,因为您必须在您的清理代码中投入很多期望,即您需要确切地知道 json 文件有什么样的错误。

但是,使用正则表达式的解决方案可能如下所示:

import json
import re

class LazyDecoder(json.JSONDecoder):
    def decode(self, s, **kwargs):
        regex_replacements = [
            (re.compile(r'([^\\])\\([^\\])'), r'\1\\\\\2'),
            (re.compile(r',(\s*])'), r'\1'),
        ]
        for regex, replacement in regex_replacements:
            s = regex.sub(replacement, s)
        return super().decode(s, **kwargs)

with open(r'C:\Yolo_v4\darknet\build\darknet\x64\result.json') as result:
    data = json.load(result, cls=LazyDecoder)

print(data)

这是通过继承标准 JSONDecoder并使用它进行加载。


推荐阅读