-1

I've been using the code below to get what I think is a JSON string from the openweathermap API.

var request = new XMLHttpRequest();

request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?lat=12&lon=-50&APPID=myKey');

request.send();

var data = JSON.parse(request.responseText);

The JSON string when I access it directly is this:

{"coord":{"lon":-50,"lat":12},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":301.461,"pressure":1025.84,"humidity":100,"temp_min":301.461,"temp_max":301.461,"sea_level":1025.82,"grnd_level":1025.84},"wind":{"speed":6.68,"deg":80.5004},"clouds":{"all":32},"dt":1507680994,"sys":{"message":0.0025,"sunrise":1507712963,"sunset":1507755824},"id":0,"name":"","cod":200}

However, when I used JSON.parse(request.responseText), I get a syntax error -- Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ()

But when I use parse on Chrome developer tools it works fine and I can access the values using their keys e.g. JSON.parse(data)['coord']['lon'] returns -50

SJC
  • 107
  • 2
  • 12

1 Answers1

1

You need to wait for the asynchronous response before trying to get the response's contents. Could be achieved this way:

request.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var data = JSON.parse(request.responseText);
  }
};
Nick
  • 16,066
  • 3
  • 16
  • 32