【问题标题】:Append New Data to JSON将新数据附加到 JSON
【发布时间】:2020-09-04 20:40:12
【问题描述】:

我正在努力将新数据附加到 JSON。我只是想从 API 调用 JSON 数据,并将其放入“匹配”下的 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"], sort_keys=True, indent = 4, separators=(',', ': ')))

file_handle["matches"].write(json.dumps(full_match_data, sort_keys=True, indent = 4, separators=(',', ': ')))

file_handle["matches"] = {**full_match_data, file_handle["matches"] sort_keys=True, indent = 4, separators=(',', ': ')))}

file_handle.write(json.dumps({"matches" : [full_match_data]}, sort_keys=True, indent = 4, separators=(',', ': ')))

file_handle.write(json.dumps(["matches" {full_match_data}], sort_keys=True, indent = 4, separators=(',', ': ')))

编辑 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

不幸的是,它不起作用。好像想了半天(是个intel pentium)然后返回一个空文件?

第二次运行它会填充文件:

{
    "matches": [
    ]
}

你能告诉我哪里出错了吗?

一旦我让它工作,我将切换到 pythonic 的方式来做它。非常感谢。

【问题讨论】:

    标签: python json riot-games-api


    【解决方案1】:

    为什么每次从 API 获得结果时都写入文件?只需将新的full_match_data 附加到列表中,并在拥有它们之后编写一次。还要注意json.dump 可以直接写入文件句柄,不需要将dumps 写入字符串然后将该字符串写入文件。

    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({"matches": matches}, file_handle)
    

    您可以用列表推导替换循环以获得更 Python 的方式:

    matches = [watcher.match.by_id(my_region, game_id) for game_id in game_ids]
    

    重新。有问题的编辑:

    我原来的回答有误。 json.dump 期望 json.dump(data, file_handle)。查看更新后的答案。


    file_handle = open(all_matches_index, "w+")
    file_handle.write('{\n    "matches": [\n    ]\n}')
    file_handle.close()
    

    这部分代码是不必要的。它所做的只是写一个空文件。无论如何,后面代码中的 with... 块应该会覆盖它。


    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({"matches": matches}, file_handle)
    

    这是将数据写入文件的部分。使用with 创建一个上下文管理器,一旦with 块结束,它会自动为您关闭文件。你可以在网上找到很多信息。


        file_handle.close
    

    这是 (a) 不必要的,因为上下文管理器无论如何都会处理关闭文件,并且 (b) 是错误的,因为您需要 调用 函数,所以 file_handle.close() 就像您之前所做的那样。

    【讨论】:

    • 这个解决方案比我的好。
    • @PranavHosangadi 我试图实施您的解决方案,但没有成功。您可以查看我编辑的问题吗?
    • @PranavHosangadi 谢谢你,非常感谢你的帮助。
    【解决方案2】:

    当您在 python 中加载 JSON 对象时,它通常只是一个字典。您可以像将数据添加到字典一样将数据添加到 JSON。在我看来,您似乎希望所有匹配项都位于最终文件中的键 matches 下。如果是这种情况,您可以创建所有匹配项的列表或字典,然后将它们添加到 matches 键下,如下所示

    match_dict= {'match_1':match_1,'match_2':match_2,...,'match_n':match_n}
    matches={'matches':match_dict}
    

    如果您想对现有的 JSON 文件执行此操作,只需使用 JSON 包读取该文件,然后执行上述操作,并在最后保存文件。

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 1970-01-01
      • 2013-03-31
      • 2018-05-14
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 2018-08-27
      相关资源
      最近更新 更多