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

How to remove {} from a JSON file

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": [
    {},
]

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

>Solution :

You can filter out the content of songs easily with a list-comprehension:

data["songs"] = [song for song in data["songs"] if song]
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