这是我的代码:
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 文件的两行中?
最佳答案
你需要在它们之间写一个换行符;只需添加 .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))
关于python - 将两个字典转储到 json 文件中的不同行上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51232080/