How to update json file with python

I'm trying to update existing Json file, but from some reason, the requested value is not being changed but the entire set of values (with the new value) is being appended to the original file

jsonFile = open("replayScript.json", "r+") data = json.load(jsonFile) tmp = data["location"] data["location"] = "NewPath" jsonFile.write(json.dumps(data)) 

and the result is : Required:

{ "location": "NewPath", "Id": "0", "resultDir": "", "resultFile": "", "mode": "replay", "className": "", "method": "METHOD" } 

Actual:

{ "location": "/home/karim/storm/project/storm/devqa/default.xml", "Id": "0", "resultDir": "", "resultFile": "", "mode": "replay", "className": "", "method": "METHOD" } { "resultDir": "", "location": "pathaaaaaaaaaaaaaaaaaaaaaaaaa", "method": "METHOD", "className": "", "mode": "replay", "Id": "0", "resultFile": "" } 

2 Answers

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile: data = json.load(jsonFile) data["location"] = "NewPath" with open("replayScript.json", "w") as jsonFile: json.dump(data, jsonFile) 

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile: data = json.load(jsonFile) data["location"] = "NewPath" jsonFile.seek(0) # rewind json.dump(data, jsonFile) jsonFile.truncate() 
6
def updateJsonFile(): jsonFile = open("replayScript.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 tmp = data["location"] data["location"] = path data["mode"] = "replay" ## Save our changes to JSON file jsonFile = open("replayScript.json", "w+") jsonFile.write(json.dumps(data)) jsonFile.close() 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like