This is the view from my browser:
{
"data": {
"request": [{
"query": "Lat 41.85 and Lon -87.65",
"type": "LatLon"
}],
"time_zone": [{
"localtime": "2012-02-14 16:05",
"utcOffset": "-6.0"
}]
}
}
Now, I am using this code to parse it:
function getTimeZone(latlong) {
jQuery(document).ready(function ($) {
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=[removed]&q=" + latlong + "&format=json",
dataType: "jsonp",
success: function (parsed_json) {
console.log(parsed_json.time_zone.utcOffset);
return parsed_json.time_zone.utcOffset;
},
error: function (parsed_json) {
//console.log("Error: " + parsed_json);
}
});
});
}
Every time I run the code, I am getting this error:
Uncaught TypeError: Cannot read property 'utcOffset' of undefined
Any assistance would be greatly appreciated.
View of the data being displayed to the console (only copied the part I’m interested in):
Result:
Object
data: Object
request: Array[1]
time_zone: Array[1]
0: Object
localtime: "2012-02-14 16:46"
utcOffset: "-6.0"
Actually, there are two issues:
1) to access the content, you need:
parsed_json.data.time_zone[0].utcOffset;
2) This is a bit more complex – you are using an asynchronous ajax callback – success() is not being called before your program finishes sending the ajax request and returns, and it does not return its results to the parent method.
The basically can’t do it the way you want to, unless you use a synchronous fetch (a bad idea, since it’ll lock up your browser until the response arrives).
Instead, take a callback parameter, which will be a function, as a parameter to your function, and call that with the result once it arrives:
i.e.
Then to use it: