I am trying to print out a list of JSON object attributes. I also tried to print out an individual ob object’s attribute. The printout to the console indicates that I am opening the file and receiving the two objects and sub objects okay. However, I am making a mistake somewhere in trying to cycle through the objects and print them out an attribute of each.
...
<script type="text/javascript">
var dta1;
$(document).ready(function() {
$.ajax({
type : "GET",
url : "data/data5.json",
success : function test(data) {
dta1 = data.object1;
dta2 = data.object2;
console.log("object1", dta1);
console.log("object2", dta2);
}
});
});
</script>
</head>
<body>
<script type="text/javascript">
for(i in dta1){
document.write(dta1[i].x);
}
document.write(dta1["object11"].x);
</script>
</body>
Here’s the json file.
{
"object1": {
"object11": {"x": "10", "y": "20", "z": "30"},
"object12": {"x": "40", "y": "50", "z": "60"},
"object13": {"x": "70", "y": "80", "z": "90"}
},
"object2": {
"object21": {"x": "100", "y": "200", "z": "300"},
"object22": {"x": "400", "y": "500", "z": "600"},
"object23": {"x": "700", "y": "800", "z": "900"}
}
}
Your second script block will run before the one in the head due to your use of the jQuery “document ready” handler which only runs after the document has fully loaded.
Also, you can’t rely on an asynchronous request (AJAX) completing before your next block of code runs. Anything that uses data retrieved via AJAX should be called within the “success” callback.
What you should probably do is create a container element in your HTML, eg
and append the values to that within your AJAX success callback, eg