为什么JSON.parse适用于Google开发人员工具,而不适用于我的js文件?

时间:2017-10-11 00:38:21

标签: javascript json

我一直在使用下面的代码来获取openweathermap API中我认为的JSON字符串。

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);

我直接访问它时的JSON字符串是:

{"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}

但是,当我使用JSON.parse(request.responseText)时,我收到语法错误 - 未捕获的SyntaxError:JSON输入的意外结束     在JSON.parse()

但是,当我在Chrome开发者工具上使用解析时,它工作正常,我可以使用他们的密钥访问这些值,例如JSON.parse(data)['coord']['lon']返回-50

1 个答案:

答案 0 :(得分:1)

在尝试获取响应内容之前,您需要等待异步响应。可以通过这种方式实现:

request.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var data = JSON.parse(request.responseText);
  }
};