Reputation: 347
I have a local JSON data file from which I need to extract data. The path is correct and works properly in other files. However it doesnt seem to be working here.
My JSON file is as below:
{
"Phone": {
"Samsung":[{
"Size" : "AAA",
"Camera" : "BBB",
"Weight" : "CCC"
}],
"Apple":[{
"Size" : "XXX",
"Camera" : "YYY",
"Weight" : "ZZZ"
}]
}
}
My jQuery is as below:
<body>
<div id="AboutTab">
<div id=About class="OuterFlexContainer">
</div>
</div>
</body>
<script>
$(document).ready(function(){
var StatJSON;
jQuery.getJSON("/TrialJSON/JSONData/QueryJSONData.json", function (json) {
StatJSON = json;
console.log(StatJSON);
});
var markup = '';
markup += '<div>'+ StatJSON.Phone.Samsung[0].Size +'<div>'
markup += '<div>'+ StatJSON.Phone.Apple[0].Size +'<div>'
$("#About").html(markup);
});
</script>
Where am I going wrong? The JSON path is fine, the error appears to be in the jQuery.
Upvotes: 0
Views: 45
Reputation: 1347
The variable StatJSON
is being populated in the callback to getJSON
, which means that when you're trying to use StatJSON
for generating the markup, it hasn't been populated yet.
Try moving the markup generation to inside the callback and it should work,
$(document).ready(function(){
var StatJSON;
jQuery.getJSON("/TrialJSON/JSONData/QueryJSONData.json", function (json) {
StatJSON = json;
console.log(StatJSON);
var markup = '';
markup += '<div>'+ StatJSON.Phone.Samsung[0].Size +'<div>'
markup += '<div>'+ StatJSON.Phone.Apple[0].Size +'<div>'
$("#About").html(markup);
});
});
Upvotes: 1