在循环中,我试图将键和值对添加到我的json文件中。
在第一次迭代中,json文件始终为空。
在第二次迭代中,我想向我的键“文章”中添加一个新的键和值。但这不起作用。我有问题。
谢谢您的提示!
问题:
list indices must be integers or slices, not set
我的方法:
keywordJson = [{'articles': [{'id': filename, 'phrases': phrases}]}]
with open(json_path, "r+", encoding='utf-8') as json_file:
if i == 0:
json_decoded = keywordJson
json.dump(keywordJson, json_file, ensure_ascii=False)
else:
json_decoded = json.load(json_file)
json_decoded[{"articles"}] = [{"id": filename, "phrases": phrases}]
json.dump(json_decoded, json_file, ensure_ascii=False)
答案 0 :(得分:1)
当您说[{"articles" : <whatever>}]
时,方括号表示此数据结构是包含单个元素的列表,该元素是字典。因此,您需要类似的东西:
json_decoded[0]["articles"] = [{"id": filename, "phrases": phrases}]
不过,我不确定您实际上是否想要所有这些列表。这可能更干净:
keywordJson = {'articles': {'id': filename, 'phrases': phrases}}
然后代码将是:
json_decoded["articles"] = {"id": filename, "phrases": phrases}