在 For 循环中增量追加到 JSON 文件

elj*_*o67 2 python api json for-loop

有没有办法在 python 的 for 循环中将单个 JSON 对象附加到 json 文件。我不想将所有数据存储在一个巨大的 json 对象中并一次全部转储,因为我计划执行数百万个 API 请求。我想发出一个 API 请求,将结果转储到 JSON 文件中,然后移动到下一个 API 请求并将其转储到同一个JSON 文件中。

下面的代码覆盖了 JSON 文件,我正在寻找附加的东西。

for url in urls:
    r = sesh.get(url)
    data = r.json()

    with open('data.json', 'w') as outfile:
        json.dump(data, outfile)
Run Code Online (Sandbox Code Playgroud)

这样:

with open('data.json') as outfile:
    data = json.load(data, outfile)

type(data)
>> dict
Run Code Online (Sandbox Code Playgroud)

r.json 看起来像这样:

{'attribute1':1, 'attribute2':10}
Run Code Online (Sandbox Code Playgroud)

Z-B*_*one 5

更新

好吧,因为我无法访问您的 API,所以我只是在数组中以您提供的格式放置了一些示例响应。

import json

urls = ['{"attribute1":1, "attribute2":10}', '{"attribute1":67, "attribute2":32}', '{"attribute1":37, "attribute2":12}'];
json_arr = []

for url in urls:
    data = json.loads(url)
    json_arr.append(data)
    with open('data.json', 'w') as outfile:
        json.dump(json_arr, outfile)
Run Code Online (Sandbox Code Playgroud)

基本上我们保留一个数组并将每个 API 响应附加到该数组。然后,我们可以将累积的 JSON 写入文件。此外,如果您想在不同的代码执行中更新相同的 JSON 文件,您可以在代码的开头将现有的输出文件读入一个数组,然后继续我的示例。



将写入模式更改为追加

尝试改变这个:

with open('data.json', 'w') as outfile:
Run Code Online (Sandbox Code Playgroud)

对此:

with open('data.json', 'a') as outfile:
Run Code Online (Sandbox Code Playgroud)