我有一个 Python 脚本,它生成一个包含无效 JSON 的文件。
现在我想操作这个 JSON 文件,使其成为有效的 JSON 文件,方法是在每个对象之间添加一个逗号,在文件的开头添加一个“[”,在结尾添加一个“]”。
有没有办法单独使用 JSON 来实现这一点,还是我必须找到一种使用其他读写函数的方法?
Exsample_File.json:
{
"firstName": "Bidhan",
"lastName": "Chatterjee",
"age": 40,
"email":"[email protected] /cdn-cgi/l/email-protection"
}
{
"firstName": "hanbid",
"lastName": "jeeChatter",
"age": 10,
"email":"[email protected] /cdn-cgi/l/email-protection"
}
....
n times
新文件.json:
[
{
"firstName": "Bidhan",
"lastName": "Chatterjee",
"age": 40,
"email":"[email protected] /cdn-cgi/l/email-protection"
},
{
"firstName": "hanbid",
"lastName": "jeeChatter",
"age": 10,
"email":"[email protected] /cdn-cgi/l/email-protection"
},
....
n times
]
这是生成 JSON 文件的函数。我不想触及生成字符串的其他代码。
data = json.loads(str)
with open('Example_File.json','ab')as outfile:
json.dump(data, outfile, indent=2)
到目前为止我还没有解决这个问题的想法。所以没有可以提供帮助的代码示例。
结果应该类似于新文件