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()
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Assuming you have a test.json file with the following content:
{"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:
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:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
Method 2
You need to update the output of json.load with a_dict and then dump the result.
And you cannot append to the file but you need to overwrite it.
Method 3
json_obj=json.dumps(a_dict, ensure_ascii=False)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0