在我看来,我正在解析一个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的内容,因为名称在循环的每次迭代中都会发生变化。我上面尝试的是导致运行时错误。如果我用voteongids评论该行,一切正常。我该如何解析解析JSON ?!任何帮助赞赏:)我正在使用钛,但出于这些目的,它只是javascript!
答案 0 :(得分: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);
答案 1 :(得分: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");
}
它会以更简单的方式显示所有键和对应的值