Reputation: 55
Newbie here, I am trying to access temperature from the OpenWeatherMap API for a project from FreeCodeCamp. But my problem is that whenever I attempt to access the temperature value using the nested JSON object, the console suggests the parent of "temp" is undefined. Why is it undefined?
This is the code that is giving me problems:
$.getJSON(url, function(data) {
console.log("successful request");
console.log(data.main.temp);
console.log("successful temperature access");
});
When I run this, the console logs "successful request," then gives me the error:
Uncaught TypeError - Cannot read property 'temp' of undefined(...).
Things I have tried: I looked at sample code and referred to the API documentation, and saw data.main.temp
was a valid method of accessing temperature. I verified that the data
object was parsed and made sure that it was not contained in an array. Also, I have verified the url. Here is a beginning snippet of what the URL leads to:
link.
Working off Chrome. Link to Codepen project.
Upvotes: 1
Views: 5264
Reputation: 55
Figured it out! I downloaded a chrome extension JSON formatter, which allowed me to see that main was actually an element under list
. The correct call was data.list[0].main.temp
!
Upvotes: 0
Reputation: 7777
The weather data comes back as a string. You need to parse it into JSON like this:
$.getJSON(url, function(data) {
var weatherData = JSON.parse(data.content);
console.log("successful request");
console.log(weatherData.main.temp);
console.log("successful temperature access");
});
Upvotes: 1