我有一個XMLHttpRequest
後以下JSON響應:如何打印JSON字符串的嵌套對象的值?
{
"success":true,
"result":{"1":{"id":"1","question":"What is one + two","answer":"three"},
"2":{"id":"2","question":"two + four","answer":"six"},
"3":{"id":"3","question":"one + three","answer":"for"}
}
}
我要顯示所有符號列表中的項目符號列表中並排側的問題和所有的答案。現在,我有以下的(包括我這個code添加JSON.parse
功能,應該工作):
<script type="text/javascript" src="json2.js"></script>
// ...
var response = JSON.parse(xhr.requestText);
var list = document.getElementById('listQuestions');
for (var i = 0 ; i < response.length; i++){
list.innerHTML += '<li>' + response[i].question + '</li>'; // I'm certain this is wrong--I also tried the following but it's not what I'm looking for:
// for (var key in response) {
// console.log("Key: "+key+" value: "+response[key]);
// }
}
// ...
</script>
您可以創建的jsfiddle? –
你的「響應」是一個對象,而不是一個數組。 'response.length'不存在。另外,你不需要遍歷'response.result'(這也是一個對象)嗎? –
@RocketHazmat所以我通過執行'for(var key in response.result){}'然後'console.log(response.result [key])來訪問響應對象中的結果對象? – Iteration