这是我的代码:
import json
data1 = {"example1":1, "example2":2}
data2 = {"example21":21, "example22":22}
with open("saveData.json", "w") as outfile:
json.dump(data1, outfile)
json.dump(data2, outfile)
输出是这样的:
{“ example2”:2,“ example1”:1} {“ example21”:21,“ example22”:22}
当我希望输出是这样时:
{“ example2”:2,“ example1”:1}
{“ example21”:21,“ example22”:22}
那么我如何在两行中将data1和data2字典转储到同一json文件中?
答案 0 :(得分:1)
您需要在它们之间写一个换行符;只需添加一个.write('\n')
调用即可:
with open("saveData.json", "w") as outfile:
json.dump(data1, outfile)
outfile.write('\n')
json.dump(data2, outfile)
这将产生有效的JSON lines输出;通过遍历文件中的各行并使用json.loads()
,再次加载数据:
with open("saveData.json", "r") as infile:
data = []
for line in infile:
data.append(json.loads(line))