如何将document.getElementById()。textContent用于嵌套的JSON数据?

问题描述 投票:0回答:1

我正在尝试从OpenWeatherMap的API访问一些嵌套数据,这是我正在使用的示例:

{
   "coord":{
      "lon":-74.46,
      "lat":40.55
   },
   "weather":[
      {
         "id":800,
         "main":"Clear",
         "description":"clear sky",
         "icon":"01d"
      }
   ],
   "base":"stations",
   "main":{
      "temp":67.93,
      "feels_like":68.72,
      "temp_min":64.99,
      "temp_max":70,
      "pressure":1022,
      "humidity":77
   },
   "visibility":16093,
   "wind":{
      "speed":4.7,
      "deg":100
   },
   "clouds":{
      "all":1
   },
   "dt":1592439281,
   "sys":{
      "type":1,
      "id":5874,
      "country":"US",
      "sunrise":1592386010,
      "sunset":1592440257
   },
   "timezone":-14400,
   "id":0,
   "name":"Piscataway",
   "cod":200
}

现在在我的用于从API获取数据的函数中,我尝试做如下操作:

var weatherURL = 'http://api.openweathermap.org/data/2.5/weather?zip=08854,us&appid=(api key hidden for privacy)&units=imperial';
    async function getWeather() {
        const response = await fetch(weatherURL);
        const data = await response.json();
        console.log(data);
        const {name, temp} = data;
        document.getElementById('currentCity').textContent = name;
        document.getElementById('temp').textContent = data["main"]["temp"];
    }

。textContent = name可以按照我的预期工作,但是如何纠正函数的最后一行,以便可以访问main.temp例如?

javascript html json openweathermap
1个回答
0
投票

您可以像data.main.temp这样访问该对象,并像data.name这样来访问名称>

简化的工作代码:

 var weatherURL = 'http://api.openweathermap.org/data/2.5/weather?zip=08854,us&appid=(api key hidden for privacy)&units=imperial';
        async function getWeather() {
            const response = await fetch(weatherURL);
            const data = await response.json();
            console.log(data);
            document.getElementById('currentCity').textContent = data.name;
            document.getElementById('temp').textContent = data.main.temp;
        }

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.