'How to delete an element in a json file python

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



Solution 1:[1]

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)

Solution 2:[2]

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)

Solution 3:[3]

Try this:

# importing the module
import ast
  
# reading the data from the file
with open('dictionary.txt') as f:
    data = f.read()
  
print("Data type before reconstruction : ", type(data))
      
# reconstructing the data as a dictionary
a_dict = ast.literal_eval(data)

{"names":[a for a in a_dict["names"] if a.get("name") !="XY_MAGIC#1111"]}

Solution 4:[4]

import json
with open("test.json",'r') as f:
   data = json.loads(f.read())
   names=data.get('names')
   for idx,name in enumerate(names):
      if name['name']=='XY_MAGIC#1111':
         del names[idx]
         break
   print(names)

In order to read the file best approach would be using the with statement after which you could just use pythons json library and convert json string to python dict. once you get dict you can access the values and do your operations as required. you could convert it as json using json.dumps() then save it

Solution 5:[5]

This does the right thing useing the python json module, and prettyprints the json back to the file afterwards:

import json

jsonpath = '/path/to/json/file.json'

with open(jsonpath) as file:
    j = json.loads(file.read())

names_to_remove = ['XY_MAGIC#1111']

for element in j['names']:
    if element['name'] in names_to_remove:
        j['names'].remove(element)
        
with open(jsonpath, 'w') as file:
    file.write(json.dumps(j, indent=4))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sakib Hasan
Solution 2
Solution 3 Nguy?n V? Trung Hi?u
Solution 4
Solution 5 Ukulele