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

标签 javascript html openweathermap

大家好!

所以,最近我想学习如何使用 API,并且我认为 openweathermap API 可能真的很有趣。我成功地让 API 请求返回一个值,但在当前状态下它无法使用。有谁知道如何拆分此字符串应用程序以将此处的每个值设置为变量?

这是我正在使用的调用:

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 (它有一种困惑的 API)与较新的 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);
  });

关于javascript - 如何分解 openweathermap API 返回的这个长字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66505350/

相关文章:

javascript - 通过附加到 html 标签的 IE10 类来定位 IE10

javascript - 通过 Object.defineProperty 添加原型(prototype)属性覆盖构造函数属性

javascript - 用于 XMLHttpRequest 或 ActiveXObject 的 JavaScript 中 jQuery 的 .ajaxComplete() 替代方案

javascript - 将 box-shadow 添加到表列(从上到下)?

javascript防止复制/粘贴超出文本区域中的字符限制

html - 是否存在一个完全没有意义的字符实体?

javascript - 获取HTML元素隐藏值

ios - 如何使 Http 请求在 TableView 单元格之前按时加载

javascript - 将天气 API 与 JSON 和 JavaScript/jQuery 结合使用

javascript - 为什么我的 JavaScript 函数没有触发?