I am writing code that will remove specific element if the user chooses to do so. It deletes the information in the brackets, but doesn’t delete the brackets themselves. Does anyone know what I am doing wrong?
`with open(filename, 'r') as fp:
data = json.load(fp)
for dict in data['songs']:
if song in dict["SongName"]:
songpath = (dict['Path'])
for stuff in data["songs"]:
if song in stuff["SongName"]:
del stuff["SongName"]
if stuff["Path"]==songpath:
del stuff["Path"]
with open(filename, 'w') as fp:
json.dump(data, fp,sort_keys=True, indent=4, separators=(",", ":"))`
What it returns:
"songs": [
{},
]
>Solution :
You can filter out the content of songs easily with a list-comprehension:
data["songs"] = [song for song in data["songs"] if song]