问题描述
我正在努力将新数据附加到JSON。我只是想从API调用JSON数据,然后将其放入“ matches”下的JSON文件中。我正在创建一个包含以下内容的空白JSON文件,然后从那里开始。
{
"matches": [
]
}
这是我的代码,尽管我怀疑只有最后一行很重要:
print ("No records found...\n Creating new match history bank.")
file_handle = open(all_matches_index,"w+")
file_handle.write('{\n "matches": [\n ]\n}')
for game_id in game_ids:
full_match_data = watcher.match.by_id(my_region,game_id)
#this is the problem line:
file_handle.write(json.dumps({"matches" : full_match_data },sort_keys=True,indent = 4,separators=(',',': ')))
我尝试了很多不同的解决方案,但似乎没有地方可以解决这个问题,或者至少我不了解自己在读什么。我知道这是一个简单的问题,但我无法解决。
一些我尝试过的例子:
file_handle.write(json.dumps(full_match_data["matches"],': ')))
file_handle["matches"].write(json.dumps(full_match_data,': ')))
file_handle["matches"] = {**full_match_data,file_handle["matches"] sort_keys=True,': ')))}
file_handle.write(json.dumps({"matches" : [full_match_data]},': ')))
file_handle.write(json.dumps(["matches" {full_match_data}],': ')))
编辑1:基于Pranav Hosangadi的回复进行的更改
首先,感谢您的答复,它包含的信息远远超过简单的修复方法,对我的学习很有帮助。
我更改了代码,现在看起来如下:
file_handle = open(all_matches_index,"w+")
file_handle.write('{\n "matches": [\n ]\n}')
file_handle.close()
matches = []
for game_id in game_ids:
full_match_data = watcher.match.by_id(my_region,game_id)
matches.append(full_match_data)
with open(all_matches_index,"w") as file_handle:
json.dump(file_handle,{"matches": matches})
file_handle.close
不幸的是,它不起作用。似乎想了一段时间(是英特尔奔腾),然后返回一个空文件?
再次运行它会用以下命令填充文件:
{
"matches": [
]
}
您能告诉我我要去哪里吗?
一旦它起作用,我将切换到pythonic方法。非常感谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)