I wish to loop through my JSON array returned by my API [{"a":1},{"b":2},{"c":3},{"d":4}]
. How do parse the JSON key and value onto my html so the output div gives only the key and value.
<body>
<div id = "result" style = "color:green" ></div>
<script type = "text/javascript">
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/api/",
type: 'GET',
dataType: 'json',
success: function(res) {
console.log(res);
//var data=$.parseJSON(res);
//var data = JSON.stringify(res)
$.each(res, function(key, value) {
console.log(key);
console.log(value);
var para = document.createElement("P");
para.innerHTML = key + ":" + value;
document.getElementById("result").appendChild(para);
})
}
});
})
</script>
</body>
2
Answers
You are looping through array ,function will take arguments as
item
andindex
:Make a secondary loop and iterate through objects:
Your JSON format is an array, with each key an object
So this means that when you loop through the items, the
key
will be the index of the array, and thevalue
will be the objectSo there are 2 options, you can either change your API to return a single object with the key:value pairs like this
Or you need to add an extra loop in your code, so that you can loop through the objects and display the values (although I would recommend to rather go with the first option