I've tried to write a script for parsing a JSON file stored in the server and returning its pairs of key/values into list items containing the relevant attributes in colon-separated format.
I've attempted to do it by using native javascript commands. Although the file is parsed successfully and you can realize that by calling for distinct elements with reference numbers (eg. myObject.pets[1].animal
or myObject.pets.length
) the loop inside the code that is supposed to capture all items is not working.
Here is the code
<!DOCTYPE html>
<html>
<body>
<ul id="animals"></ul>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObject = JSON.parse(this.responseText);
var finalString = "";
for (i in myObject.pets.length) {
var currentItem = "<li>" + myObject.pets[i].animal + ": " + myObject.pets[i].name + "</li>";
var finalString = finalString.concat(currentItem);
}
document.getElementById("animals").innerHTML = finalString;
}
};
xmlhttp.open("GET", "animals.json", true);
xmlhttp.send();
</script>
</body>
</html>
The JSON file
>animals.json
{
"pets":[
{ "animal":"dog", "name":"Fido" },
{ "animal":"cat", "name":"Felix" },
{ "animal":"hamster", "name":"Lightning" }
]
}
and the expected outcome
<li>dog: Fido</li>
<li>cat: Felix</li>
<li>hamster: Lightning</li>