Sandeep Singh
Sandeep Singh

Reputation: 8010

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": "", "Name": "ABC"}

My code is as follow:

with open(file_name, 'w') as file:
            for data in results:
                saveData = {}
                for k,v in data.items():
                    if v:
                        saveData[k] = v
                    else:
                        saveData[k] = ''
                print (json.dumps(saveData))
                file.write(json.dumps(saveData, ensure_ascii=False))
        file.close()

What I need it as below format:

{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}
{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}

I tried several ways from the various answer from StackOverflow, however, I am unable to get it? Is there any way to do it?

Upvotes: 0

Views: 15427

Answers (2)

DirtyBit
DirtyBit

Reputation: 16792

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"}

Upvotes: 4

andreihondrari
andreihondrari

Reputation: 5833

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")

Upvotes: 3

Related Questions