Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append in a json file in Python?

Tags:

python

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() 
like image 819
PythonEnthusiast Avatar asked Sep 24 '13 11:09

PythonEnthusiast


People also ask

How do you append data into a JSON file in Python?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

How do I update an existing JSON file in Python?

Updating a JSON object in Python is as simple as using the built-in update() function from the json package we have imported. The update method is used to add a new key-value pair to the JSON string that we declared in our code.

How do I add a JSON file to another JSON file?

JSON doesn't have any mechanism to reference/include JSON in other files. You manually have to edit the JSON and insert your other JSON there. Or load both JSON files with whatever language you are processing the data in, and write some custom logic to merge the data in that language.

Which function is used to append data using JSON?

So using array function all data is stored in array format and then it converts into JSON data with the use of json_encode() function. If the file already exists, we can append it with that old data. file_get_contents() function will get the current data in a file then we can add new data.


2 Answers

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.

like image 73
alecxe Avatar answered Sep 20 '22 14:09

alecxe


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.

like image 24
Nicolas Barbey Avatar answered Sep 20 '22 14:09

Nicolas Barbey