gpt4 book ai didi

javascript - 如何使用纯 JavaScript 解析来自 API 的 JSON?

转载 作者:行者123 更新时间:2023-11-28 04:46:31 24 4
gpt4 key购买 nike

我知道这个问题会以不同的方式被问到,但我正在努力思考如何处理从 API URI 返回的数据,并希望更清楚地了解如何正确使用它。

我正在练习 API,并决定制作一个简单的天气应用程序,从 openweathermap.com 获取数据

示例 URI 为 http://api.openweathermap.org/data/2.5/weather?q=Los+Angeles&APPID=myApiKey

我使用页面上的输入来连接这些数据,该输入填充您输入的任何城市或邮政编码,并将完整路径打印为链接,效果很好。但是当我尝试解析此 URI 中的数据时,出现错误

Uncaught SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at getWeather (index.js:25)
at HTMLButtonElement.onclick

我正在尝试分解此 API 数据中的数据,以便我可以适本地显示温度、风、湿度等内容。

这是我编写的代码,用于测试我是否正确获取数据。

// Set API variables
const api = "http://api.openweathermap.org/data/2.5/weather?q=";
const apiKey ="myAPIKey";

// Set City and Units
let unitType = "imperial";
let units = "&units=" + unitType;

function setup() {
var button = document.getElementById('submit');
button.click = getWeather();
}


function getWeather() {
let city = document.getElementById('city').value;
let fullPath = api + city + "&APPID=" + apiKey + units;

console.log(city);
//document.getElementById('weatherData').innerHTML='<a href="' + fullPath + '">' + city + '</a>';

let data = fullPath;
let obj = JSON.parse(data);
document.getElementById('weatherData').innerHTML = obj.main.temp;
}

当您单击页面上的提交按钮时,将调用 getWeather() 函数,如下所示:

<!doctype html>
<html>
<head></head>
<body>
<input type="text" id="city" placeholder="Enter a city" />
<button onclick="getWeather()" id="submit">Submit</button>
<div id="weatherData" style="background: #ccc; padding: 20px; margin-top: 25px;">
</div>


<script src="index.js"></script>
</body>
</html>

我做错了什么?我以前从未使用过 API,所以如果我看起来很无知,请原谅我。当我让程序在屏幕上打印一个串联的 URL(链接到 URI 本身)时,它就可以工作,但现在我尝试实际提取数据时,我收到了上面的错误。

编辑这里是返回的 API 数据的示例:

{
"coord": {
"lon": -96.81,
"lat": 32.78
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 295.15,
"pressure": 1016,
"humidity": 78,
"temp_min": 294.15,
"temp_max": 296.15
},
"visibility": 20921,
"wind": {
"speed": 4.1,
"deg": 180
},
"clouds": {
"all": 100
},
"dt": 1491835980,
"sys": {
"type": 1,
"id": 2596,
"message": 0.0099,
"country": "US",
"sunrise": 1491825755,
"sunset": 1491872065
},
"id": 4684888,
"name": "Dallas",
"cod": 200
}

最佳答案

let fullPath = api + city + "&APPID=" + apiKey + units; // fullPath is a string representing an URL
let data = fullPath; // data is a string representing an URL
let obj = JSON.parse(data); // You try to parse an URL, not JSON

您尝试解析 URL,但它不起作用。在此 URL 上发出 XHR 请求以获取您的 JSON 数据。

编辑:

要请求远程 JSON 文件,请使用 fetch API(如果您的浏览器未实现 fetch,请包含 polyfill):

fetch('/data.json')
.then(function(response) {
return response.json();
}).then(function(json) {
console.log('parsed json', json);
}).catch(function(ex) {
console.log('parsing failed', ex);
})

关于javascript - 如何使用纯 JavaScript 解析来自 API 的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43326503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com