Home > database >  How to delete an element in a json file python
How to delete an element in a json file python

Time:04-07

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

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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))
  • Related