Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an element in a json file python

Tags:

python

json

I am trying to delete an element in a json file,

here is my json file:

before:

{
    "names": [
        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "Brody B#3719",
            "points": 0
        },
        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "XY_MAGIC#1111",
            "points": 0
        }
    ]
}

after running script:


{
    "names": [
        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "Brody B#3719",
            "points": 0
        }
    ]
}

how would I do this in python? the file is stored locally and I am deciding which element to delete by the name in each element

Thanks

like image 923
SPEEDBIRD101 Avatar asked Oct 17 '25 13:10

SPEEDBIRD101


2 Answers

You will have to read the file, convert it to python native data type (e.g. dictionary), then delete the element and save the file. In your case something like this could work:

import json

filepath = 'data.json'
with open(filepath, 'r') as fp:
    data = json.load(fp)
del data['names'][1]

with open(filepath, 'w') as fp:
    json.dump(data, fp)
like image 139
Sakib Hasan Avatar answered Oct 20 '25 02:10

Sakib Hasan


I would load the file, remove the item, and then save it again. Example:

import json
with open("filename.json") as f:
    data = json.load(f)
f.pop(data["names"][1]) # or iterate through entries to find matching name
with open("filename.json", "w") as f:
    json.dump(data, f)
like image 35
Professor Dragon Avatar answered Oct 20 '25 04:10

Professor Dragon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!