0

在我看来,我正在解析一个不是最好的 JSON 响应。以下是实际响应:

[
    {"challenge_id":"39029"},
    {"song1_id":"198","name":"PRAY","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/TAKE_THAT_-_PRAY.mp3"},
    {"song2_id":"251","name":"THE TEARS OF A CLOWN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/SMOKEY_ROBINSON_-_THE_TEARS_OF_A_CLOWN.mp3"},
    {"song3_id":"11","name":"WONDERFUL TONIGHT","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ERIC_CLAPTON_-_WONDERFUL_TONIGHT.mp3"},
    {"song4_id":"288","name":"THE NAME OF THE GAME","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ABBA_-_THE_NAME_OF_THE_GAME.mp3"},
    {"song5_id":"159","name":"I'M EVERY WOMAN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/CHAKA_KHAN_-_I'M_EVERY_WOMAN.mp3"},
    {"status":"ok"}
]

这是我解析它的尝试:

var challenge_Songs = JSON.parse(this.responseText);

for(var i = 1; i<challenge_Songs.length-1; i++){
    challengeSongs[i-1] = challenge_Songs[i].url;
    challengeTitles[i-1] = challenge_Songs[i].name;
    voteSongIds[i-1]= challenge_Songs.song[i]_id;
}

我的问题是获取我设置为 voteSongIds 的内容,因为名称在循环的每次迭代中都会发生变化。我在上面尝试过的是导致运行时错误。如果我用 votesongids 评论这条线,一切正常。我应该如何解析解析 JSON?!任何帮助表示赞赏:) 我正在使用钛,但出于这些目的,它只是 javascript!

4

2 回答 2

2

这是你要找的结果吗?

var challenge_Songs  = [
{"challenge_id":"39029"},
{"song1_id":"198","name":"PRAY","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/TAKE_THAT_-_PRAY.mp3"},
{"song2_id":"251","name":"THE TEARS OF A CLOWN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/SMOKEY_ROBINSON_-_THE_TEARS_OF_A_CLOWN.mp3"},{"song3_id":"11","name":"WONDERFUL TONIGHT","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ERIC_CLAPTON_-_WONDERFUL_TONIGHT.mp3"},
{"song4_id":"288","name":"THE NAME OF THE GAME","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ABBA_-_THE_NAME_OF_THE_GAME.mp3"},
{"song5_id":"159","name":"I'M EVERY WOMAN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/CHAKA_KHAN_-_I'M_EVERY_WOMAN.mp3"},{"status":"ok"}]

var challengeTitles=[], 
    challengeSongs = [], 
    voteSongIds=[];

for(var i = 1; i < challenge_Songs.length-1; i++){
    challengeTitles.push(challenge_Songs[i]['name']);
    challengeSongs.push(challenge_Songs[i]['url']);
    voteSongIds.push(challenge_Songs[i]['song'+ i +'_id'])
}

console.log(challengeTitles);
console.log(challengeSongs);
console.log(voteSongIds);
于 2013-10-01T09:16:17.900 回答
0

试试下面的代码。无论关键或价值如何,这都将完美无缺

for(var i = 0; i<challenge_Songs.length; i++){
  for(key in challenge_Songs[i]){
   console.log("\n key=>" + key + " : value=> " + challenge_Songs[i][key]);
  }
  console.log("\n");
}

它将以更简单的方式向您显示所有键和对应的值

于 2013-10-01T09:40:28.210 回答