2016-07-22 42 views
0

我有一個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> 
+0

您可以創建的jsfiddle? –

+2

你的「響應」是一個對象,而不是一個數組。 'response.length'不存在。另外,你不需要遍歷'response.result'(這也是一個對象)嗎? –

+0

@RocketHazmat所以我通過執行'for(var key in response.result){}'然後'console.log(response.result [key])來訪問響應對象中的結果對象? – Iteration

回答

3

在你的JSON響應結果屬性是一個對象,而不是一個數組。此外,響應變量不指向結果對象,而是指向父容器對象,因此您必須通過調用response.result來訪問結果對象。

var jsonText = '{"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"}}}'; 
 
var response = JSON.parse(jsonText); 
 
var list = document.getElementById('listQuestions'); 
 
var results = Object.keys(response.result); 
 
for (var i = 1 ; i <= results.length; i++) { 
 
    list.innerHTML += '<li>' + response.result[i].question + ' - ' + response.result[i].answer + '</li>'; 
 
}
<div id="listQuestions"> 
 

 
</div>

https://jsfiddle.net/djqrt8z9/

0
let response = JSON.parse(xhr.requestText); 
let qs = []; 
for (let obj of response.result) qs.push("<li>"+obj.question+"<\/li>"); 
document.getElementById('listQuestions').innerHTML = qs.join(''); 

上面使用for ... of構建物通過對象的值循環。

1

根據你的描述,我不確定你是否想要兩個列表,因爲你說你想要一個問題列表和項目符號列表。

var response = { 
 
    "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"} 
 
    } 
 
} 
 
var questions = document.getElementById('listQuestions'); 
 
var answers = document.getElementById('listAnswers'); 
 

 
var result = response.result 
 

 
Object.keys(result).forEach(function(key){ 
 
    var question = document.createElement('li'); 
 
    questions.appendChild(question); 
 
    question.innerHTML = result[key].question; 
 
    
 
    var answer = document.createElement('li'); 
 
    answers.appendChild(answer); 
 
    answer.innerHTML = result[key].answer; 
 
})
<ul id="listQuestions"></ul> 
 
<ul id="listAnswers"></ul>

相關問題