如何在python中删除特定的json值?



我正在制作一个播放列表网站,可以创建显示和删除播放列表和歌曲。我使用JSON文件来存储数据。唯一不能用的功能是删除歌曲功能。

这是我的JSON文件
"Playlists": [
{
"ID": 1,
"Name": "Car Boosted",
"Songs": [
{
"Name": "Dusk Till Dawn",
"Artist": "Sia",
"Link": "https://www.youtube.com/watch?v=6ADdqsvlqtU"
},
{
"Name": "Blinding Lights",
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
}
],
"Date": "16 / 03 / 2022"
},
{
"ID": 2,
"Name": "Workout Playlists",
"Songs": [
{
"Name": "Dusk Till Dawn",
"Artist": "Sia",
"Link": "https://www.youtube.com/watch?v=6ADdqsvlqtU"
},
{
"Name": "Blinding Lights",
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
},
{
"Name": "Till I Collapes",
"Artist": "Eminem",
"Link": "https://www.youtube.com/watch?v=Obim8BYGnOE"
},
{
"Name": "Lose Yourself",
"Artist": "Eminem",
"Link": "https://www.youtube.com/watch?v=_Yhyp-_hX2s"
}
],
"Date": "25 / 04 / 2022"
}
]

我使用播放列表的ID和歌曲的索引来定位它在列表中,并使用它来删除它。这是我的deleteSong"功能:

def deleteSongFromJson(songID, pid):
"""deletes Songs Form Playlist
Args:
songID (int): ID Of Song
id (itn): ID Of Playlist
"""
pid = int(pid)
songID = int(songID)
with open('databse.json','r+') as file:
data = json.load(file)
playlists = data['Playlists']
for playlist in playlists:
if playlist['ID'] == id:
songs = playlist["Songs"]
del songs[songID]
file.seek(0)
json.dump(data, file, indent = 4)

当我运行该函数时,它从右播放列表中删除歌曲,但粘贴列表的最后一位,并粘贴到JSON文件的底部。

"Name": "Blinding Lights",
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
}
],
"Date": "17 / 05 / 2022"
}
]
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
}
],
"Date": "17 / 05 / 2022"
}
]

我认为你的问题是试图一次读取和写入文件,这会导致奇怪的光标问题。

尝试重构你的代码,使其有两个独立的open语句,如下所示(未测试):

def deleteSongFromJson(songID, pid):
"""deletes Songs from Playlist
Args:
songID (int): ID Of Song
id (itn): ID Of Playlist
"""
pid = int(pid)
songID = int(songID)
with open('databse.json','r') as file:
data = json.load(file)
for playlist in data['Playlists']:
if playlist['ID'] == id:
del playlist["Songs"][songID]
with open('databse.json','w') as file:
json.dump(data, file, indent=4)

相关内容

  • 没有找到相关文章

最新更新