简体   繁体   English

如何在 Python 中追加 json 文件?

[英]How to append in a json file in Python?

I have the a json file whose contents is {"67790": {"1": {"kwh": 319.4}}} .我有一个 json 文件,其内容是{"67790": {"1": {"kwh": 319.4}}} Now I create a dictionary a_dict which I need to append it into the json file.现在我创建了一个字典a_dict ,我需要将它附加到 json 文件中。 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()

Assuming you have a test.json file with the following content:假设您有一个test.json以下内容的test.json文件:

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

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:然后,下面的代码将load json 文件,使用dict.update()更新里面的数据并dumptest.json文件中:

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)

Then, in test.json , you'll have:然后,在test.json ,您将拥有:

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

Hope this is what you wanted.希望这是你想要的。

You need to update the output of json.load with a_dict and then dump the result.您需要使用 a_dict 更新 json.load 的输出,然后转储结果。 And you cannot append to the file but you need to overwrite it.您不能附加到文件,但需要覆盖它。

json_obj=json.dumps(a_dict, ensure_ascii=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM