skip to Main Content

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


  1. Assuming that you have a JS dictionary listed above and it is in variable weather. You could access it using JS code like this:

    let lat = weather[0]["lat"];
    let lon = weather[0]["lon"];
    

    The reason why you don’t use

    let lat = weather[0].lat;
    let lob = weather[0].lon;
    

    is because it is actually a dictionary, not an JS object.

    Login or Signup to reply.
  2. i don’t know which shape has your API response body, but could you try this :

    fetch(coordRequestPath)
    .then(function(response){
        
        cityLat = response?.data?.[0]?.lat;
        cityLon = response?.data?.[0]?.lon;
        console.log("Latitude: " + cityLat + " Longitude: " + cityLon);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search