Search code examples
javascriptapixmlhttprequest

How to get JSON response from public API into JSON object?


I'm attempting to get some data from the OpenWeatherMap API. When I send the request with the required API key and location data, everything returns back fine. The returned data appears to be in JSON format. However, when I perform the JSON.parse() function on the string, it gives an error of "unexpected end of input".

One thing that I found interesting was that if I was to store the string into a variable and then proceed to execute the function in Chrome's debug console, it completes fine.

let jsonData;
let jsonActual;
function GetWeather(city, country){
  Http = new XMLHttpRequest();
  Http.open("GET", weatherUrl + city + "," + country + weatherKey);
  Http.send();
  Http.onreadystatechange=(e)=>{
    jsonData = Http.response;
    jsonActual = JSON.parse(jsonData.toString());

  }
}

On using the console:

x = JSON.parse(jsonData) // Completes successfully

Solution

  • Your readyState is never checked if it is complete:

    Http.onreadystatechange = e => {
        if (this.readyState == "complete") {
            jsonData = Http.response;
            jsonActual = JSON.parse(jsonData.toString());
        }
    }
    

    You could also check against 4:

    Http.onreadystatechange = e => {
        if (this.readyState == 4) {
            jsonData = Http.response;
            jsonActual = JSON.parse(jsonData.toString());
        }
    }
    

    And you could just make it even simpler and use fetch:

    let jsonData;
    let jsonActual;
    function GetWeather(city, country){
        fetch(`${weatherUrl}${city},${country}${weatherKey}`).then(res => res.json()).then(res => {
            jsonData = res;
            jsonActual = JSON.parse(res);
        });
    }