【问题标题】:How to use document.getElementById().textContent for nested JSON data?如何将 document.getElementById().textContent 用于嵌套的 JSON 数据?
【发布时间】:2020-10-07 23:02:59
【问题描述】:

我正在尝试从 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】:

    您可以像这样data.main.temp 访问该对象并像这样命名data.name

    简化的 jQuery 代码:

     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);
                //Append Results
                $('#currentCity').html(data.name)
                $('#temp').html(data.main.temp)
    
            }
    

    var data = {
       "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
    }
    
    //Append Results
    $('#currentCity').html(data.name)
    $('#temp').html(data.main.temp)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="weather_details">
      
    </div>
    
    <h3>Current Weather for <span id="currentCity"></span>
    </h3><div class="weather_details">
       <p>Temperature: <span id="temp"></span>
       </p> 	
    </div>

    希望这会有所帮助。

    【讨论】:

    • 我必须使用您提供的脚本吗?因为我需要它不断地从 API 中获取数据。
    • 我们越来越近了——我还在接近Uncaught (in promise) TypeError: Cannot set property 'textContent' of null at getWeather,我的主要目标是在

      标记内的 中使用它。

    • @MatthewVandenberg 您是否可以选择使用 jQuery 或者您只想使用 javascript 来执行此操作?
    • 哪个更容易。抱歉,我是网络编程新手。
    • @MatthewVandenberg 确定。使用 jQuery 和使用 append() 会更容易,我已经更新了我的答案,我将在 span 中使用名称,在 p 中使用温度。
    【解决方案2】:
    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, main: { temp }} = data; // Destructuring
        document.getElementById('currentCity').textContent = name;
        document.getElementById('temp').textContent = temp; // Same with name example above
    }
    

    你可以试试这个吗? 没有太多改变你的代码。

    注意:您也可以使用 temp.toFixed(1) 将温度设为 67.9 而不是 67.93。

    【讨论】:

    • 似乎不起作用,错误:Uncaught (in promise) TypeError: Cannot set property 'textContent' of null at getWeather
    • 这个错误听起来像是异步获取有问题。因为您已经获取数据const response = await fetch(weatherURL); 并等待。然后你解析数据const data = await response.json(); 并等待。数据已经存在。我相信肯定还有另一个问题。
    • @MatthewVandenberg 我刚刚尝试获取并实际工作。我建议检查代码的异步部分。 const {name, main: { temp }} = data; // Destructuring console.log("name", name); console.log("temp", temp.toFixed(1)); 输出为:name London temp 292.4
    猜你喜欢
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多