Home > Software engineering >  Getting API Data to show on a webpage with Javascript
Getting API Data to show on a webpage with Javascript

Time:07-12

I'm trying to get data from https://wttr.in/?format=j1 to show on a webpage. I'm very new to Javascript so I hoped this would be easy but I'm struggling to get it to work, what am I doing wrong?.

<html lang="en">
 
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content=
    "width=device-width, initial-scale=1.0" />
</head>
 
<body>
    <p id="temp"></p>
</body>
<script>
  const api_url = "https://wttr.in/?format=j1";
 
  async function getWeather() {
   
    const response = await fetch(api_url);
 
    const data = await response.json();
    
    const weather = data.results[0].current_condition[0];
    
    let { temp } = weather.temp_C;
    
    document.getElementById("temp").href = "temp:"   temp;
 
  getWeather();
  
</script>
 
</html>

CodePudding user response:

As per the comments from CBroe (thanks for the help) the main issues with my code were a few things.

  • No closing bracket
  • Not accessing the correct part of the JSON array
  • Not setting the element correctly

The working code looks like this:

<html lang="en">
 
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content=
    "width=device-width, initial-scale=1.0" />
</head>
 
<body>
    <p id="temp"></p>
</body>
<script>
  const api_url = "https://wttr.in/?format=j1";
 
  async function getWeather() {

    const response = await fetch(api_url);
 
    const data = await response.json();
    
    const weather = data.current_condition[0];
    
    let temp = weather.temp_C;
    
    document.getElementById("temp").innerHTML = "temp:"   temp;
}
  getWeather();
  
</script>
</html>

CodePudding user response:

You are not parsing the json response correctly. The data does not have any results array, it is an object.

So to get current_condition you need to do something like this:

    const currentCondition = data.current_condition[0];

Also, to get temp_C this is wrong:

let { temp } = weather.temp_C; //WRONG
// reason is that this statement means that `temp_C` is an object, and it contains `temp` property, which is not the case here. Because temp_C is a string.

So to get temp_C you need to simply do this:

    let temp_C = currentCondition.temp_C;

Plus, worth mentioning here that if you are using the temp_C only for displaying purposes and not intending to reassign any value to it, then its better to use const instead of let

So it would become:

    const temp_C = currentCondition.temp_C;

And if you want to use 'destructuring' you need to write it like this:

    const { temp_C } = currentCondition;

Also your function is missing the closing paranthesis }.

  • Related