如何打印JSON字符串的嵌套对象的值?

时间:2016-07-22 17:21:12

标签: javascript arrays json object

我在XMLHttpRequest后面有以下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>

3 个答案:

答案 0 :(得分:3)

JSON响应中的result属性是一个对象而不是一个数组。此外,响应变量不指向结果对象,而是指向父容器对象,因此您必须通过调用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/

答案 1 :(得分: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>

答案 2 :(得分: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构造来遍历对象的值。