
本文详解如何正确解析 openweathermap 等 restful api 返回的嵌套 json 对象,提取城市名、温度、湿度、风速等关键字段,并动态渲染到 html 表格中,避免初学者常见的 promise 时序错误、数据结构误判和 dom 操作陷阱。
本文详解如何正确解析 openweathermap 等 restful api 返回的嵌套 json 对象,提取城市名、温度、湿度、风速等关键字段,并动态渲染到 html 表格中,避免初学者常见的 promise 时序错误、数据结构误判和 dom 操作陷阱。
在使用 fetch() 获取天气 API 数据时,许多初学者会遇到“数据看起来很乱”“取不到字段”“页面无反应”等问题——这通常并非 API 数据本身“混乱”,而是对响应结构理解不足、Promise 链处理不当、或 DOM 操作逻辑错位所致。OpenWeatherMap 的 /weather 接口返回的是单个对象(Object),而非数组(Array),因此不能直接调用 .forEach();其核心数据位于嵌套属性中,如 data.name、data.main.temp、data.wind.speed 等。
以下是一个健壮、可扩展的实现方案:
✅ 正确结构:分离关注点 + 明确作用域
const getDataButton = document.getElementById("get-data-button");
const table = document.getElementById("weather");
// ✅ 将渲染逻辑封装为独立函数,接收解析后的 data 对象
function displayJson(data) {
// ✅ 创建新表格行
const row = table.insertRow();
// ✅ 按顺序插入单元格(对应表头:City / Temp (C°) / Humidity / Wind Speed)
row.insertCell().textContent = data.name || 'Unknown City';
row.insertCell().textContent = parseFloat((data.main?.temp - 273.15).toFixed(2)) || '—';
row.insertCell().textContent = data.main?.humidity ?? '—';
row.insertCell().textContent = data.wind?.speed ?? '—';
}
// ✅ 事件监听器内专注发起请求,Promise 链清晰闭环
getDataButton.addEventListener("click", () => {
// ? 可选:读取用户输入的城市名(需配合地理编码 API 或 city 参数)
const cityInput = document.getElementById("place").value.trim();
const apiKey = "30967b695a09a50b12dd726193281aa5";
// ⚠️ 注意:当前示例仍使用固定经纬度;生产环境应替换为 city 查询(如 ?q=Seattle&appid=...)
const url = `https://api.openweathermap.org/data/2.5/weather?lat=47.6&lon=-122.3&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
return response.json();
})
.then(displayJson)
.catch(err => {
console.error("❌ 数据获取失败:", err);
alert(`无法获取天气信息:${err.message}`);
});
});? HTML 与 CSS 补充(确保基础可用性)
<label for="place">Enter a City Name:</label>
<input type="text" id="place" placeholder="e.g., London, Tokyo">
<button id="get-data-button">Submit</button>
<table id="weather" style="margin-top: 1rem; border-collapse: collapse;">
<thead>
<tr>
<th style="padding: 8px; border: 1px solid #ccc;">City</th>
<th style="padding: 8px; border: 1px solid #ccc;">Temp (°C)</th>
<th style="padding: 8px; border: 1px solid #ccc;">Humidity (%)</th>
<th style="padding: 8px; border: 1px solid #ccc;">Wind Speed (m/s)</th>
</tr>
</thead>
<tbody></tbody>
</table>⚠️ 关键注意事项
- 不要在 .then() 外访问 data:data 仅在 displayJson(data) 函数参数中有效,切勿在外部作用域引用;
- 避免全局变量:displayJson 必须用 function 声明(或 const displayJson = (...) => {...}),禁止隐式挂载到 window;
- 防御性编程:使用可选链(?.)和空值合并(??)防止 undefined 报错,提升鲁棒性;
- 单位转换说明:OpenWeatherMap 默认返回开尔文(K),需减去 273.15 转为摄氏度;添加 &units=metric 参数可直接获取 °C;
- 下一步升级建议:将固定经纬度替换为用户输入城市名,需调用 geocoding API(如 https://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${key})先获取坐标,再查天气。
掌握 JSON 路径定位与 Promise 生命周期,是前端数据驱动开发的核心能力——每一次 console.log(data) 后,先展开观察顶层结构,再逐层点击确认字段路径,比盲目试错高效十倍。


















