gpt4 book ai didi

python - 从多个字典写入单个 JSON

转载 作者:行者123 更新时间:2023-12-02 08:43:27 25 4
gpt4 key购买 nike

我正在尝试通过将多个(可能是 20 个)字典逐个附加/转储到 JSON 文件中,将多个字典写入单个 json 文件中,到目前为止,我已经完成了以下代码来完成,但我不能。如果有人知道更好的方法,请提供帮助

run1 = client.send_get('get_tests/11023')
run2 = client.send_get('get_tests/11038')

with open('result.json', 'w') as fp:
json.dump(run1, fp)

最佳答案

我不确定这是否可能。当您读回文件内容时,您期望什么?

当您从文件中读取某些内容时,它应该是有效的 json 才能加载。一种选择是创建一个像这样的字典

d = dict(run1 = run1, run2 = run2, ... )

然后将 json.dump d 本身放入文件中。

更新:这是一个例子。这使用列表而不是字典(基于您的评论),但想法是相同的。

run1 = dict(status = "ok", message = "All good")
run2 = dict(status = "error", message = "Couldn't connect")

def save_data(*runs):
with open("foo.json", "w") as f:
json.dump(list(runs), f)

def load_data(fname):
with open(fname) as f:
return json.load(f)


save_data(run1, run2)
outputs = load_data("foo.json")
print (outputs)

[{'status': 'ok', 'message': 'All good'}, {'status': 'error', 'message': "Couldn't connect"}]

关于python - 从多个字典写入单个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59476056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com