Home > Blockchain >  Update Json file from Python script
Update Json file from Python script

Time:09-29

I have a json file with this format :

{ "list": [ { "key1" : "value1", "key2" : "value2" }, { "key1" : "value1", "key2" : "value2" } ] }

I need to read all items of my file and update the key2 but new value. My issus that my script create new item and not update the current.

list= open('file.json','r ')
data = json.load(list)
for item in data['list']:
 item.update(key2="newValue")
 json.dump(item,list)
list.close

I want the result like this :

{ "list": [ { "key1" : "value1", "key2" : "newValue" }, { "key1" : "value1", "key2" : "newValue" } ] }

CodePudding user response:

You will need to read the file and close it. Then update the structure, then write it back to the file. These are the three steps:

with open('file.json') as f:
    data = json.load(f)

for item in data['list']:
    item.update(key2="newValue")

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