Skip to content

Python write JSON to file

  • by

Use json.dumps() method to write JSON to file in Python. Create a JSON file using the open(filename, ‘w’) function and Use file.write(text) to write JSON content.

json.dump(j_data, outfile, indent=4)

indent – defines the number of units for indentation

You can convert any Python object to a JSON string and write JSON to File using json.dumps() function and file.write() function respectively.

Python writes JSON to file example

Simple example code.

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

import json

with open('data_file.json', 'w') as outfile:
json.dump(j_data, outfile, indent=4)

Output:

Python writes JSON to file

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

Source: https://stackoverflow.com/questions/55591341/

How do I write JSON data stored in the dictionary data to a file?

Answer: data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

See json documentation.

Source: https://stackoverflow.com/questions/12309269/

Do comment if you have any doubts or suggestions on this Python write file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading