I’m making a request to a weather API and getting this response back:
[
{
"name": "Old Toronto",
"local_names": {
"gr": "Τορόντον",
"ug": "تورونتو",
"he": "טורונטו הישנה",
"fa": "تورنتو",
"pl": "Toronto",
"ku": "Toronto",
"en": "Old Toronto",
"el": "Παλαιό Τορόντο",
"de": "Toronto",
"ar": "تورونتو القديمة",
"pa": "ਟੋਰਾਂਟੋ",
"oc": "Toronto",
"ur": "پرانا ٹورانٹو",
"es": "Toronto",
"ca": "Toronto",
"ps": "ټورنټو",
"fr": "Toronto",
"pt": "Toronto",
"hy": "Տորոնտո"
},
"lat": 43.6534817,
"lon": -79.3839347,
"country": "CA",
"state": "Ontario"
}
]
How do I access the "lat" and "lon" data via javascript/Jquery?
I though the correct way to access this would be "response. lat" and "response.lon" but these come up as undefined. I noticed that the response is wrapped in ‘[]’ so I have also tried "reponse[0].lat" which had the same result
Edit: Added code snippet of request:
fetch(coordRequestPath)
.then(function(response){
cityLat = response[0].lat;
cityLon = response[0].lon;
console.log("Latitude: " + cityLat + " Longitude: " + cityLon);
})
2
Answers
Assuming that you have a JS dictionary listed above and it is in variable
weather
. You could access it using JS code like this:The reason why you don’t use
is because it is actually a dictionary, not an JS object.
i don’t know which shape has your API response body, but could you try this :