如何在Python中附加json文件? [英] How to append in a json file in Python?

查看:171
本文介绍了如何在Python中附加json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容为{"67790": {"1": {"kwh": 319.4}}}的json文件.现在,我创建一个字典a_dict,我需要将其附加到json文件中.我尝试了以下操作,但无法正确执行.我要去哪里错了?

I have the a json file whose contents is {"67790": {"1": {"kwh": 319.4}}}. Now I create a dictionary a_dict which I need to append it into the json file. I tried the following but was not able to do it correctly. Where I'm going wrong?

with open(DATA_FILENAME, 'a') as f:
   json_obj = json.dump(a_dict, json.load(f)
   f.write(json_obj)
   f.close()

推荐答案

假定您有一个具有以下内容的test.json文件:

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

然后,下面的代码将load json文件,使用dict.update()dump将内部数据更新为test.json文件:

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

然后,在test.json中,您将拥有:

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

希望这就是您想要的.

这篇关于如何在Python中附加json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆