Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a json file from list

Tags:

python

json

I have the following list data I want to save in a json file to be access later:

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

If saved as txt:

for item in data:
    with open('./data/awards.txt', 'w', encoding='utf-8') as f:
        f.write(', '.join(str(item) for item in data))

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

But I get an error when opening the file later in Jupyter Notebook

If save as json

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

Output with extra backslash:
"{\"nomineesWidgetModel\":{\"title\":\"\",\"description\":\"\",\"refMarker\":\"ev_nom\", 
 \"eventEditionSummary\":{\"awards\":[{\"awardName\":\"Oscar\",\"trivia\":[],}]}}

Is there a simpler way to do this without having to import the file and replace the extra slashes?

like image 683
lela_rib Avatar asked Jun 17 '26 02:06

lela_rib


1 Answers

Just use json as usual:

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)
like image 176
moctarjallo Avatar answered Jun 18 '26 16:06

moctarjallo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!