如何分解 openweathermap API 返回的这个长字符串?

How can I break down this long string returned by the openweathermap API?

大家好!

所以,最近我想学习如何使用 API,我觉得 openweathermap API 会很有趣。我成功地获得了返回值的 API 请求,但在其当前状态下无法使用。有谁知道我如何拆分这个字符串 Appart 以将这里的每个值设置为变量?

这是我正在使用的电话:

var request = new XMLHttpRequest();
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q={not a real city}&appid={censored}', true); //not a real id
request.onload = function() {
    console.log(request.response);
}
request.send();

我需要尝试使用的响应类似于:

{"coord":{"lon":-85.4898,"lat":42.9595},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":267.51,"feels_like":262.69,"temp_min":265.93,"temp_max":269.26,"pressure":1026,"humidity":74},"visibility":10000,"wind":{"speed":2.57,"deg":270},"clouds":{"all":1},"dt":1615029875,"sys":{"type":1,"id":4269,"country":"US","sunrise":1615032556,"sunset":1615073839},"timezone":-18000,"id":4993125,"name":"Forest Hills","cod":200}

所以是的,^^ 是我需要尝试打破的。我可以使用 string.split() 很多次,但这对我来说真的很乱。我觉得必须有一种我不知道的更好的方法。我知道这可能真的很简单,但是,这还是我第一次使用 API。我还尝试在互联网(以及 Stack 此处)上搜索答案,但找不到答案。

谢谢!

正如@JoshG 提到的,您可以使用 JSON.parse(...) 将任何 JSON 字符串解析为 javascript 对象。

另一种方法是替换您当前使用的旧 XMLHttpRequest api (which has a kind of messy API) with the newer fetch api(更容易)。

例如:

fetch('http://api.openweathermap.org/data/2.5/weather?q={not a real city}&appid={censored}')
  .then(res => res.json())
  .then(function(res) {
    console.log(res);
  });