Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update Json file from Python script

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading