9

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()
1

4 Answers 4

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you provide a concrete example?
There is a missing colon : on line 5 - first code category with open('my_file.json', 'w') as f:
2

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))

2 Comments

@DrV point taken, another with block is probably cleaner than seek(0)
@timgeb: seek is also a nice solution, see my answer.
1

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)

Comments

0
  • 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()

1 Comment

Code-only posts are discouraged on Stack Overflow. Your answer could be much improved by adding supporting information and explanations. See how to write a good answer for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.