Ram K
Ram K

Reputation: 1785

Creating a file of json objects from a list of dicts

I have a list of dictionaries in python as follows:

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.

If i do f.write(json.loads(json.dumps(d))) its the same as writing the dict and everything is in single quotes .

I want a file of json objects one per line all with double quotes. What am i missing ?

Upvotes: 0

Views: 316

Answers (1)

buhtz
buhtz

Reputation: 12152

You have to use the json.dump() (without the s in the function name!) with a file object.

#!/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"
        }
    }
]

Upvotes: 2

Related Questions