简体   繁体   English

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

[英]Creating a file of json objects from a list of dicts

I have a list of dictionaries in python as follows: 我在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)

Now I write them to a file as follows : 现在,我将它们写入文件,如下所示:

for d in list_of_dicts:
    f.write(d)

In the file all my double quotes get converted to single quotes 在文件中,我所有的双引号都转换为单引号

If i do f.write(json.dumps(d)) everything becomes a string with the backslash character added , but i don't want this , I want to retain them as JSON objects in the file. 如果我执行f.write(json.dumps(d))所有内容都将成为添加了反斜杠字符的字符串,但我不希望这样做,我想将其作为JSON对象保留在文件中。

If i do f.write(json.loads(json.dumps(d))) its the same as writing the dict and everything is in single quotes . 如果我做f.write(json.loads(json.dumps(d)))它与编写字典相同,并且所有内容都用单引号引起来。

I want a file of json objects one per line all with double quotes. 我想要每行一个带双引号的json对象文件。 What am i missing ? 我想念什么?

You have to use the json.dump() (without the s in the function name!) with a file object. 您必须将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)

Results in 结果是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM