You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何访问DWD API以数字为键的嵌套天气数据?

问题

之前用OpenWeatherMap API展示天气数据一切正常,现在复用代码调用德国气象服务DWD API时遇到问题。DWD返回的JSON顶级键是气象站ID(如10384),导致无法访问嵌套数据,终端报错:Parsing error: Unexpected token, expected "}"。

DWD API返回的JSON结构示例:

{
  "10384": {
    "forecast1": {
      "stationId": "10384",
      "start": 1664834400000,
      "timeStep": 3600000,
      "temperature": [],
      "temperatureStd": [],
      "windSpeed": null,
      "windDirection": null,
      "windGust": null,
      "icon": [],
      "precipitationTotal": [],
      "precipitationProbablity": null,
      "precipitationProbablityIndex": null
    },
    "forecastStart": null,
    "days": [
      {
        "stationId": null,
        "dayDate": "2022-10-04",
        "temperatureMin": 93,
        "temperatureMax": 157,
        "icon": 3,
        "icon1": null,
        "icon2": null,
        "precipitation": 0,
        "windSpeed": 111,
        "windGust": 296,
        "windDirection": 2740,
        "sunshine": 1920
      }
    ]
  }
}

将获取到的JSON存入data状态变量后,想要访问10384->forecast1->temperature和10384->days->temperatureMin,但数字键无法用常规方式访问,现有代码片段如下:

useEffect(() => {
  const getData = async () => {
    try {
      const response = await 
    fetch('https://dwd.api.proxy.bund.dev/v30/stationOverviewExtended?stationIds=433,10384'
        ,{
          method: "GET",
          mode: "cors",
          headers: {"content-type": "application/json" }
        }
       
      )
      if (!response.ok) {
        throw new Error(
          `HTTP error. Status: ${response.status}`
        );
      }
      let actualData = await response.json();
      setData(actualData);
      console.log(actualData);
      setError(null);

    } catch(err) {
      setError(err.message);
      setData(null);
    } finally {
      setLoading(false);
    }
  }
  getData()
}, [])

return (
  <div>
    {loading && <div>Loading...</div>}
    {error && (
      <div>{`Fehler beim Fetchen von Daten. Error fetching data - ${error}`}</div>
    )}
      <div className="widget-container">

          {/* Temepraturausgabe + Wetter-Icon*/}
          <div className="temp-container">
            <span className="tempNow">{data.10384? <h1>{data.10384.days}: null}</span>
          </div>
      </div>
  </div>
);

请问为何数字键无法访问?如何正确获取这些嵌套天气数据?


解答

为什么数字键不能用点语法访问?

JavaScript的对象点语法要求键名必须是合法标识符:不能以数字开头,不能包含特殊字符(仅允许_和$)。数字开头的键(如10384)不符合规则,因此data.10384会触发语法错误。

正确访问数字键的方法

1. 方括号语法(直接访问)

用字符串形式的键名通过方括号访问,这是最直接的解决方案:

// 访问forecast1下的temperature数组
data["10384"].forecast1.temperature

// 访问days数组第一个元素的temperatureMin
data["10384"].days[0].temperatureMin

2. 遍历多站点数据

如果请求了多个气象站(示例中为433,10384),可以用Object.keys()或Object.entries()遍历所有顶级键:

// 获取所有气象站ID数组
const stationIds = Object.keys(data);

// 遍历每个站点数据
stationIds.forEach(stationId => {
  const stationData = data[stationId];
  console.log(`站点${stationId}最低温:`, stationData.days[0].temperatureMin);
});

3. 解构赋值(提前提取数据)

在获取数据后直接解构出目标站点的数据,后续使用更简洁:

let actualData = await response.json();
// 解构出10384站点的数据
const { "10384": station10384 } = actualData;
setData(station10384);
// 后续直接使用station10384.forecast1.temperature即可

修复代码中的语法错误

你的return部分存在语法错误(无效的data.10384?、标签未闭合),修复后示例:

return (
  <div>
    {loading && <div>Loading...</div>}
    {error && (
      <div>{`Fehler beim Fetchen von Daten. Error fetching data - ${error}`}</div>
    )}
    {/* 添加空值判断,避免数据未加载时报错 */}
    {data && (
      <div className="widget-container">
        <div className="temp-container">
          <span className="tempNow">
            <h1>{data["10384"].days[0].temperatureMin}</h1>
          </span>
        </div>
      </div>
    )}
  </div>
);

内容的提问来源于stack exchange,提问作者random030

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:45:19