0

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 ?

buhtz
  • 10,774
  • 18
  • 76
  • 149
Ram K
  • 1,746
  • 2
  • 14
  • 23
  • Can you give an example about what is in your file and what do you want in your file. Your question is not clear for me. – buhtz Jun 14 '19 at 22:31
  • If you dump to json file correctly, It should automatically have double quotes, since json doesn't support single quotes – WiseDev Jun 14 '19 at 22:31
  • 2
    Possible duplicate of [How do I write JSON data to a file?](https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file) – slider Jun 14 '19 at 22:33
  • 1
    Also, don't do f.write(...). Use json.dump() directly (not json.dumps which is for dumping to strings rather than files) – WiseDev Jun 14 '19 at 22:33

1 Answers1

2

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"
        }
    }
]
buhtz
  • 10,774
  • 18
  • 76
  • 149
  • the inner dict (address) becomes like this if i do the above : "address": { "\State\" : \"FL\" }.. how to remove the escape chaarcters ? – Ram K Jun 14 '19 at 22:46
  • How do you open/view the file? Which python interpreter do you use on which operating system? – buhtz Jun 14 '19 at 22:56