修复 llm_result.json 文件以供 json.load() 解析
修复 llm_result.json 文件以供 json.load() 解析
假设 llm_result.json 文件包含一些额外的文本,导致它无法被 Python 的 json.load() 方法解析。本文提供了一个代码示例,可以有效地修复此问题。
原始文件内容示例:
Based on the provided JSON, here are the generated test cases:
{
"case_1": {
"steps": [
"点击(393, 242)的'奖品B'输入框",
"输入'奖品名称'",
"点击(393, 325)的'70'输入框",
"输入'50'",
"点击(393, 474)的'奖品发放说明内容B'输入框",
"输入'发放说明'",
"点击(459, 732)的'3'输入框" ]
}
}
在如下 python 代码基础上修改:将llm_result.json前面的内容删除,使llm_result.json可以被json.load()方法解析
with open('llm_result.json') as f:
lines = f.readlines()
index = len(lines) - 1
while index >= 0:
# print(index)
if lines[index].strip() == "},":
break
index -= 1
del lines[index + 1:]
lines[index] = lines[index][:-2]
lines.append('
}')
with open('llm_result.json', 'w') as file:
file.writelines(lines)
解决方案:
以下 Python 代码可以删除 llm_result.json 文件中最后一组键值对后的部分,使文件可以被 json.load() 方法解析。
with open('llm_result.json') as f:
lines = f.readlines()
index = len(lines) - 1
while index >= 0:
if lines[index].strip() == "},":
break
index -= 1
del lines[:index]
lines[-1] = lines[-1][:-2]
lines.append('
}')
with open('llm_result.json', 'w') as file:
file.writelines(lines)
代码说明:
- 代码首先打开 llm_result.json 文件,并将所有行读入
lines列表中。 - 然后,代码从列表的最后一行开始遍历,直到找到包含
},的行。 - 找到该行后,代码将从列表中删除该行之前的所有行。
- 最后,代码删除
}之前的逗号,并在列表末尾添加一个新的空行和右括号},然后将修改后的内容写回 llm_result.json 文件。
完成上述操作后,llm_result.json 文件将仅包含有效的 JSON 数据,可以被 json.load() 方法正确解析。
原文地址: https://www.cveoy.top/t/topic/qrRU 著作权归作者所有。请勿转载和采集!