Home > OS >  How to remove {} from a JSON file
How to remove {} from a JSON file

Time:10-26

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

CodePudding user response:

Add a check if stuff is empty. If so then delete that element from list:

!cat "/content/sample_data/test.json"
[Out]:
{
    "songs": [
        {
            "SongName": "a",
            "Path": "/home"
        }
    ]
}
song = "a"

with open("/content/sample_data/test.json", '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"]
    if len(stuff.keys()) == 0:
        data["songs"].remove(stuff)

with open("/content/sample_data/test_2.json", 'w') as fp:
    json.dump(data, fp,sort_keys=True, indent=4, separators=(",", ":"))
!cat "/content/sample_data/test_2.json"
[Out]:
{
    "songs":[]
}

CodePudding user response:

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

data["songs"] = [song for song in data["songs"] if song]

CodePudding user response:

It deletes the information in the brackets, but doesn't delete the brackets themselves.

I do not know how to program the language you use. However, I am sure that you can print out the whole result and you can write it into a file. Then, you can use other language to build an exe to RpSubText. Then, you can rewrite the data to the file, by the small exe and write an ini file so that the main program can recive that this action is finished and it can read the file.

while(GetKeyText(your path and ini)!="false")// false is a text because you read an ini file. If the exe is finished, it will trun it into true
    SetKeyText(your path and ini,"false")//in order to reuse the ini
    break()

I do not program C and this may have gramma error, this is just an example may be this language can RpSubText too, but I do not know anything about it.

  • Related