JSON returning strange things in Weather App

JSON returning strange things in Weather App
0.0 0

#1

Hello, World!
I’m having issues with my weather app ( https://codepen.io/aviage-01/pen/RyOGWg) ). At the moment, I am trying to get the image to work. I have to code to retrieve the JSON, and then I alert that. However, nearly every time I alert the JSON, I get a different response. I am calling the alert directly after the JSON is returned, so I don’t think it’s an asynchronous loading issue. Here’s the code:

var lat = 0;
var lon = 0;
var weatherData = {};
$(".holding-box").hide();
if (navigator.geolocation) {
  
  navigator.geolocation.getCurrentPosition(function(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    
    $.getJSON(
      "https://fcc-weather-api.glitch.me/api/current?lon=" +
        lon +
        "&lat=" +
        lat,
      function(json) {
        
        $(".weather-description").html("");
        $(".weather-image").attr("src", JSON.stringify(json.weather[0].icon))
        alert(JSON.stringify(json.weather[0].icon)+ " and " + $(".weather-image").attr("src"))
      }
    );
  
  });
  
}

@Whoever fixed the post’s appearance, thanks very much!


#2

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

FYI - You were using three single quotes instead of three backticks.

Not sure why you are using JSON.stringify. Get rid of that and you should see an image.


#3

Thanks very much! That fixed it. :grinning:
I was using the stringify method because I thought that the attr method would want a string input. Is this not correct?


#4

Whatever you pass to attr function gets coerced to a string even if it is not. However, in this case if you look at the JSON response, json.weather[0].icon is already a string.