Iteration Iteration - 4 months ago 12
Javascript Question

How can I print values of nested objects of JSON string?

I have the following JSON response after an

XMLHttpRequest
:

{
"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"}
}
}


I want to display all the questions in a bulleted list and all the answers in a bulleted list side-by-side. Right now I have the following (I included this code to add the
JSON.parse
functionality, should work):

<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>

Answer

The result property in your JSON response is an object and not an array. Also, the response variable does not point to the result object but rather the parent, container object so you'll have to access the result object by calling 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/