Update Json file from Python script

Question:

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"
}
]
}

Asked By: Younes Ben Tlili

||

Answers:

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)
Answered By: quamrana
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.