Write Json Into File Python 3
I am trying to write JSON data into the file which is writing in one line as below: {'AbandonmentDate': '', 'Abstract': '', 'Name': 'ABC'}{'AbandonmentDate': '', 'Abstract': '', 'N
Solution 1:
Using json_dump
:
j_data = {"AbandonmentDate": "", "Abstract": "", "Name": "ABC"},{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}
import json
with open('j_data_file.json', 'w') as outfile:
json.dump(j_data, outfile,indent=4)
OUTPUT:
[
{
"AbandonmentDate": "",
"Abstract": "",
"Name": "ABC"
},
{
"AbandonmentDate": "",
"Abstract": "",
"Name": "ABC"
}
]
EDIT:
If you really want to have the elements printed on new lines, iterate over the data:
j_data = {"AbandonmentDate": "", "Abstract": "", "Name": "ABC"},{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}
import json
with open('j_data_file.json', 'w') as outfile:
for elem in j_data:
json.dump(elem, outfile)
outfile.write('\n')
OUTPUT:
{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}
{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}
Solution 2:
Assuming your json is like:
yourjson = [
{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"},
{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}
]
then you need only to do this:
with open("outfile.txt", "w") as pf:
for obj in yourjson:
pf.write(json.dumps(obj) + "\n")
Post a Comment for "Write Json Into File Python 3"