Skip to content

Write list to JSON file Python

  • by

Use the dump() function to Write a list to JSON file in Python. You can dump only object that contains objects that JSON can handle (lists, tuples, strings, dicts, numbers, None, True and False).

import json
with open('outputfile', 'w') as fout:
    json.dump(your_list_of_dict, fout)

Write a list to JSON file Python

For simple example code just write json.dump(data) to file.

import json

data = ["DisneyPlus", "Netflix", "Peacock"]

with open('OTT.json', 'w') as f:
json.dump(data, f, indent=4)

Output:

Write list to JSON file Python

Another example

import json

data = [{"nomineesWidgetModel":{"title":"","description":"", "refMarker":"ev_nom","eventEditionSummary":{"awards":[{"awardName":"Oscar","trivia":[]}]}}}]

with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)

Convert the lists to list of dictionaries and dump this to the file

arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100, 3400, 200]
with open('file.json', 'w') as file:
    json.dump([{'user': id, 'wallet amount': amount} for id, amount in zip(arr_of_id_by_user, arr_of_wallet_amount)], file

Writing a list of objects to JSON file

You should use either dumps, or dump.

def create_json():
    with open("./data/student.txt", "w") as file:
        json.dump([ob.__dict__ for ob in stList], file)

OR

def create_json():
    json_string = json.dumps([ob.__dict__ for ob in stList])
    with open("./data/student.txt", "w") as file:
        file.write(json_string)

Do comment if you have any doubts or suggestions on this Python JSON 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

Your email address will not be published. Required fields are marked *