私はその曲のIDに基づいてJSON配列オブジェクト内の1つの特定の曲を取得しようとしています。私の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変数にするだけです。
助けてください。
回答:
回答№1は0var 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);
});
});