Python 将两个字典转储到json文件中的不同行中

Python 将两个字典转储到json文件中的不同行中,python,json,dictionary,dump,Python,Json,Dictionary,Dump,这是我的代码: 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(da

这是我的代码:

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)
输出如下:

{“示例2”:2,“示例1”:1}{“示例21”:21,“示例22”:22}

当我希望输出为以下内容时:

{“示例2”:2,“示例1”:1}

{“示例21:21”,示例22: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.loads()
,再次加载数据:


当我试图加载它时,我发现这个错误:AttributeError:'str'对象没有属性'read'。。。倾销工作和我一样wanted@Caz:那是因为我打了一个愚蠢的错别字;我明确指出您需要使用
json.loads()
,但很快就忘记了在代码示例中包含尾随的
s
。现在更正。是的,我刚刚注意到
json.load()
应该是
json.load()
,但是现在如果我打印它,它会说
[{u'example2':2…
,u在哪里来自?@Caz:JSON文本始终是Unicode文本。
u'.'
告诉您有Unicode文本字符串。当您混合字符串类型时,Python 2将透明地将这些字符串编码为ASCII ByTestring。有什么方法可以摆脱它吗?和/或我可以从JSON文件加载回data1和data2吗?(不带“u”)
with open("saveData.json", "r") as infile:
    data = []
    for line in infile:
        data.append(json.loads(line))