简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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