简体   繁体   English

为什么 JSON.parse 可以在 Google 开发人员工具上使用,而不能在我的 js 文件中使用?

[英]Why does JSON.parse work on Google developer tools, but not in my js file?

I've been using the code below to get what I think is a JSON string from the openweathermap API.我一直在使用下面的代码从 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);

The JSON string when I access it directly is this:当我直接访问它时的 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}

However, when I used JSON.parse(request.responseText), I get a syntax error -- Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ()但是,当我使用 JSON.parse(request.responseText) 时,出现语法错误 -- 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 eg JSON.parse(data)['coord']['lon'] returns -50但是当我在 Chrome 开发人员工具上使用 parse 时它工作正常,我可以使用它们的键访问值,例如JSON.parse(data)['coord']['lon']返回 -50

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM