从字典列表中创建json对象文件

时间:2019-06-14 22:17:07

标签: python json python-3.x

我在python中有一个字典列表,如下所示:

A = {}
A["name"] = "Any_NameX"
A["age"] = "Any_AgeX"
A["address"] = {"city": "New York", "State": "NY"}

B = {}
B["name"] = "Any_NameY"
B["age"] = "Any_AgeY"
B["address"] = {"city": "Orlando", "State": "FL"}

list_of_dicts.append(A)
list_of_dicts.append(B)

现在我将它们写入文件如下:

for d in list_of_dicts:
    f.write(d)

在文件中,我所有的双引号都转换为单引号

如果我做f.write(json.dumps(d)),所有内容都变成一个添加了反斜杠字符的字符串,但是我不希望这样做,我想将它们作为JSON对象保留在文件中。

如果我这样做f.write(json.loads(json.dumps(d))),则与写字典一样,并且所有内容都用单引号引起来。

我想要每行一个带双引号的json对象文件。我想念什么?

1 个答案:

答案 0 :(得分:2)

您必须对文件对象使用json.dump()(在函数名中不要使用s!)。

#!/usr/bin/env python3
import json

A = {}
A["name"] = "Any_NameX"
A["age"] = "Any_AgeX"
A["address"] = {"city": "New York", "State": "NY"}

B = {}
B["name"] = "Any_NameY"
B["age"] = "Any_AgeY"
B["address"] = {"city": "Orlando", "State": "FL"}

list_of_dicts = [A, B]

with open('json.file', 'w') as f:
    json.dump(list_of_dicts, f, indent=4)

结果

[
    {
        "name": "Any_NameX",
        "age": "Any_AgeX",
        "address": {
            "State": "NY",
            "city": "New York"
        }
    },
    {
        "name": "Any_NameY",
        "age": "Any_AgeY",
        "address": {
            "State": "FL",
            "city": "Orlando"
        }
    }
]