从列表中写入一个json文件

时间:2019-12-13 17:50:38

标签: python json

我有以下列表数据,我想保存在json文件中以便以后访问:

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

如果另存为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":[]}]}}}

但是稍后在Jupyter Notebook中打开文件时出现错误

如果另存为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\":[],}]}}

是否有一种更简单的方法,而不必导入文件并替换多余的斜杠?

2 个答案:

答案 0 :(得分:0)

由于上面的@Alexander说明,我能够将要抓取的内容保存在字典中,而不是列表中,然后在使用以下方法迭代页面时另存为json:

with open('data.json', 'a') as file:
            json.dump(data, file, indent=1)

答案 1 :(得分:0)

只需照常使用json

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)