{
"Adam":{
"Math":"93",
"Science":"96",
"Email":"adam@example.com",
"City":"NY"
},
"Tom":{
"Math":"65",
"Science":"56",
"Email":"tom@example.com",
"City":"LA"
},
"Joe":{
"Math":"74",
"Science":"83",
"Email":"joe@example.com",
"City":"Washington"
}
}
Above is the JSON content present at the http: //ActualUrl/path.json
I am accessing the JSON file and filling the two arrays with name and marks in science with the code below.
var names=[];
var marks=[];
$.getJSON("http://path.json",function(data){
$.each(data, function(key, val) {
names.push(key);
// I placed alert the check the value key.
marks.push(parseInt(val.Science));
});
});
alert(names.toString()); // names is found blank
alert(marks.toString());
When I check the array at the end. Array is found blank. Why this wrong behaviour with getJSON ? I placed alert in the each and check the value. It returns correct value.
Primary problem
You are filling your array in the async callback, but alert them right away. So, this is what happens:
You execute ajax call. Request is sent to the server.
You alert values of arrays. They are blank, since the server didn’t reply yet.
Server replies, your callback is fired and arrays are filled. Too late.
Solution:
Put alert logic to the callback.
Other notes
jQuery.eachis for iterating collections. You, on the other hand, have an object (or dictionary).Try this code:
for ... in ...construct iterates object properties, which is what you want.