将两个字典分别转储到json文件中 [英] Dump two dictionaries in a json file on separate lines
问题描述
这是我的代码:
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}
当我希望输出是这样时:
When I want the output to be this:
{ example2:2, example1:1}
{"example2": 2, "example1": 1}
{ example21:21, example22:22}
{"example21": 21, "example22": 22}
那么如何在两行中将data1和data2字典转储到同一json文件中?
So how do I dump data1 and data2 dictionaries to the same json file on two separate lines?
推荐答案
您需要在它们之间写一个换行符;只需添加 .write('\n')
调用:
You'll need to write a newline between them; just add a .write('\n')
call:
with open("saveData.json", "w") as outfile:
json.dump(data1, outfile)
outfile.write('\n')
json.dump(data2, outfile)
这会产生有效的 JSON行输出;通过遍历文件中的行并使用 json.loads()
:
This produces valid JSON lines output; load the data again by iterating over the lines in the file and using json.loads()
:
with open("saveData.json", "r") as infile:
data = []
for line in infile:
data.append(json.loads(line))
这篇关于将两个字典分别转储到json文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!