我试图根据该歌曲的ID在json数组对象中获取一首特定歌曲。我的json文件看起来像这样......
文件名“playlist.json”......
"song": [
{
"songTitle": "Song Title 01",
"songDesc": "This is the description",
"songUrl": "./music/sample.mp3",
"ID": 1
},
{
"songTitle": "Song Title 02",
"songDesc": "This is the description",
"songUrl": "./music/sample.mp3",
"ID": 2
}
]
请注意,json文件中还有其他对象。这只是歌曲列表。
我已经尝试过这样做并且不断出现错误。我可以获取一行的内容,但无法弄清楚如何只获取ID为1的特定行的内容。
$(function() {
$.getJSON('playlist.json', function(data) {
$.each(data.song, function(i, f) {
if (f.ID == 1) {
var currentStation = f.songUrl
}
});});});
如你所见,我显然不知道自己在做什么。我只想返回ID = 1的行的歌曲URL,然后将该歌曲URL设为currentStation变量。
请帮忙。
答案 0 :(得分:0)
var currentStation;
$(function() {
$.getJSON('http://localhost:8080/playlist.json', function(data) {
var songs = data["song"];
for( var song_key in songs){ // Looping through songs by associating song to each javascript object found in the array.
if(songs[song_key]["ID"] == 1){
currentStation = songs[song_key]["songUrl"];
}
}
console.log(currentStation);
});
});