运行我的对象检测模型后,它将输出一个.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},
]
}
](还有几个检测到的对象,但没有包括它们)
发布于 2021-01-26 23:07:07
嗨,您需要使用double (反斜杠),删除objects属性中的最后一个逗号,最后您不需要关闭with块中的文件。
[
{
"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}
]
}
]发布于 2021-01-26 23:13:24
其他回应者当然是对的。这是无效的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并使用它来加载的。
发布于 2021-01-26 22:42:20
"\"字符不仅用于Windows文件,而且还用作换行符(例如,您可以使用"\n"而不是实际的换行符)。要逃避逃逸,只需在其前面加上第二个反斜杠,如下所示:
"C:\\Yolo_v4\\darknet\\build\\darknet\\x64\\f047.png"正如有人在评论中说的那样,json.dump应该自动为您做这件事,所以听起来像是内部的事情搞砸了(除非不是用它创建的)。
https://stackoverflow.com/questions/65910282
复制相似问题