user502052
user502052

Reputation: 15259

How to update a JSON file by using Python?

I am using Python and I have a JSON file in which I would like to update a value related to a given key. That is, I have the my_file.json containing the following data

{"a": "1", "b": "2", "c": "3"}

and I would like to just change the value related to the b key from 2 to 9 so that the updated file look as like:

{"a": "1", "b": "9", "c": "3"}

How can I make that?


I tried the following but without success (the changes are not saved to the file):

with open('my_file.json', 'r+') as f:
    json_data = json.load(f)
    json_data['b'] = "9"
    f.close()

Upvotes: 9

Views: 38412

Answers (4)

Gabriel Braico Dornas
Gabriel Braico Dornas

Reputation: 665

  • Open the file and store in one variable all the content using json.load function

  • Update your key stored in the previous variable

  • Open the file another time and update your content with the variable updated

def updateJsonFile():
    jsonFile = open("my_file.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    data["b"] = "9"

    ## Save our changes to JSON file
    jsonFile = open("my_file.json", "w+")
    jsonFile.write(json.dump(data))
    jsonFile.close()

Upvotes: 0

DrV
DrV

Reputation: 23490

You did not save the changed data at all. You have to first load, then modify, and only then save. It is not possible to modify JSON files in-place.

with open('my_file.json', 'r') as f:
    json_data = json.load(f)
    json_data['b'] = "9"

with open('my_file.json', 'w') as f:
    f.write(json.dumps(json_data))

You may also do this:

with open('my_file.json', 'r+') as f:
    json_data = json.load(f)
    json_data['b'] = "9"
    f.seek(0)
    f.write(json.dumps(json_data))
    f.truncate()

If you want to make it safe, you first write the new data into a temporary file in the same folder, and then rename the temporary file onto the original file. That way you will not lose any data even if something happens in between.

If you come to think of that, JSON data is very difficult to change in-place, as the data length is not fixed, and the changes may be quite significant.

Upvotes: 15

Suhas Jadhav
Suhas Jadhav

Reputation: 79

This is simplest way to do the json file updation/writing. where you are creating instance of json file as 'f' and the writing the 'data' into the json file,

#write json file

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

#Read json file

with open('data.json', 'r') as f:
    json.load(data, f)

Upvotes: 1

timgeb
timgeb

Reputation: 78650

You are almost there, you only have to write the updated json_data back to the file. Get rid of f.close(), as the with statement will ensure that the file is closed. Then, issue

with open('my_file.json', 'w') as f:
    f.write(json.dumps(json_data))

Upvotes: 2

Related Questions