如何通过Axios从OpenWeatherMap API响应中提取对象与数组数据?
如何从OpenWeatherMap API响应中提取嵌套对象和数组的数据
问题背景
我用以下Axios代码调用OpenWeatherMap的5天天气预报API:
const axios = require("axios"); require("dotenv").config({ path: './googlerequest/.env'}); API_key = process.env.API_KEY; lat = 55 lon = 55 url = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${API_key}` axios.get(url) .then((res) => { let data = (res.data) console.log(data) }).catch((err) => {console.log(err)})
成功获取到响应,但打印内容里的[Object]和[Array]类型字段,不知道怎么提取具体数据:
{ cod: '200', message: 0, cnt: 40, list: [ { dt: 1669388400, main: [Object], weather: [Array], clouds: [Object], wind: [Object], visibility: 231, pop: 0.2, snow: [Object], sys: [Object], dt_txt: '2022-11-25 15:00:00' } ], city: { id: 582854, name: 'Alekseyevka', coord: { lat: 55, lon: 55 }, country: 'RU', population: 3966, timezone: 18000, sunrise: 1669349428, sunset: 1669377822 } }
解决方法
你看到的[Object]和[Array]只是Node.js打印对象时的简写,实际都是嵌套结构,直接用点符号或方括号就能访问内部数据:
1. 访问嵌套对象字段
main、clouds、wind这类[Object]是嵌套对象,用.属性名直接访问:
// 提取第一条预报的温度、湿度、云量 const firstForecast = data.list[0]; console.log("温度:", firstForecast.main.temp); console.log("湿度:", firstForecast.main.humidity); console.log("云量占比:", firstForecast.clouds.all + "%");
2. 访问数组字段
weather这类[Array]是数组(通常仅含一个元素),先通过索引[0]取到数组内的对象,再访问属性:
// 提取天气描述和图标代码 const weatherDetail = firstForecast.weather[0]; console.log("天气描述:", weatherDetail.description); console.log("天气图标代码:", weatherDetail.icon);
3. 遍历所有预报数据
list数组包含40条每3小时的预报,要批量处理的话用循环遍历:
data.list.forEach(forecast => { console.log("\n---", forecast.dt_txt, "---"); console.log("温度:", forecast.main.temp); console.log("天气:", forecast.weather[0].main); console.log("降水概率:", forecast.pop * 100 + "%"); });
修改后的完整代码
const axios = require("axios"); require("dotenv").config({ path: './googlerequest/.env'}); API_key = process.env.API_KEY; lat = 55 lon = 55 // 加units=metric返回摄氏度,默认是开尔文 url = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${API_key}&units=metric` axios.get(url) .then((res) => { let data = res.data; // 打印城市基础信息 console.log("城市:", data.city.name, "(", data.city.country, ")"); // 遍历所有预报项 data.list.forEach(forecast => { console.log("\n时间:", forecast.dt_txt); console.log("温度:", forecast.main.temp, "℃"); console.log("天气状况:", forecast.weather[0].description); console.log("降水概率:", forecast.pop * 100, "%"); }); }).catch((err) => {console.log(err)})
内容的提问来源于stack exchange,提问作者Nhật Minh
相关产品推荐
相关产品推荐

