Jump to content

JSON API Help


paulmo

Recommended Posts

Displaying JSON data from weather API (that supports JSONP), "weather" parameter works, but I'm not having success with "forecast." I'm including links for brevity rather than posting JSON:

http://api.openweathermap.org/data/2.5/weather?q=portland,me&callback=hollaback

http://api.openweathermap.org/data/2.5/forecast?q=portland,me&callback=hollaback

So the following works, but when I change "weather" to "forecast" in src, I'm not able to retrieve temp or anything other than city (data.name works with "forecast"). And getting no errors in console or network window (200). Please advise how to get temp, wind, etc. from "forecast."
<script>window.hollaback = function(data) {    document.getElementById("datadiv").innerHTML = data.name + " " + data.main.temp;};</script><script src="http://api.openweathermap.org/data/2.5/weather?q=portland,me&callback=hollaback"</script>

 

Link to comment
Share on other sites

<script src="http://api.openweathermap.org/data/2.5/forecast?q=portland,me&callback=hollaback"</script> is the data structure I need help with.

window.hollaback = function(data) {        var arr = data.list;    var keys = [];    for (var key in arr) {        keys.push(key);    }    document.getElementById("datadiv").innerHTML = data.city.name + " " + keys;};

gives me: Portland 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35

 

replacing var arr = data.list; with var arr = data; gives:

Portland cod,message,city,cnt,list

 

But I need to use elements in the data, like temp, etc., and var arr = data.main.temp throws

Uncaught TypeError: Cannot read property 'temp' of undefinedjson.html:26 window.hollabackforecast?q=portland,me&callback=hollaback:1 (anonymous function)

 

 

I've tried var arr = data.temp which only outputs Portland, and no errors.

Thanks for any help accessing this JSON data structure.
Edited by paulmo
Link to comment
Share on other sites

You're getting the error because the JSON structure does not have a property called main. Have you pulled up the URL in the browser to see what the JSON structure actually looks like or are you just guessing? You need to look at the actual data structure. Other than just looking at it in the browser you can also use console.log to send the entire thing to the developer console and then you'll be able to click and expand the various parts.

Link to comment
Share on other sites

Thanks, no I'm not just guessing, I'm looking at JSON, which I will post if requested.

 

Meanwhile, this gives me one instance of "temp" (in this example, third temp, but I need all instances of).

var arr = data.list[0, 1, 2 ].main.temp;     var keys = [];    for (var key in arr) {        keys.push(key);    }    //return Object.keys(data.list);    document.getElementById("datadiv").innerHTML = data.city.name + " " + arr; //*};

* calling "keys" instead of "arr" gives me no temp at all.

 

Edited by paulmo
Link to comment
Share on other sites

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>JSON Web Service</title><style></style><script>window.onerror = function(a, b, c, d){alert('Javascript Error:n'+a+'nURL: '+b+'nLine: '+c+'  Column: '+d);return true;}</script><script>'use strict';var datobj;function myfunc1(retdata) { datobj = retdata;}window.onload = function(){   document.getElementById("outp").innerHTML = JSON.stringify(datobj);}</script><script src="http://api.openweathermap.org/data/2.5/weather?q=portland,me&callback=myfunc1"></script></head><body><div id="outp"></div></body>    </html>
Link to comment
Share on other sites

Thanks Davej, if you could help with getting results from "forecast" parameter in this JSON that would be great.

 

If I list [0] or [3] etc. in data.list below and print the "arr" variable, I get a temp. If I try a range [0 - 9], I get nothing. If I don't put the [ ] with list, I get error "temp undefined." If I print either "keys" or "key" variable (instead of arr), I get nothing. I'd like to print all the temps in the JSON.

var arr = data.list[0].main.temp;     var keys = [];    for (var key in arr) {        keys.push(key);    } document.getElementById("datadiv").innerHTML = data.city.name + " " + arr;
Edited by paulmo
Link to comment
Share on other sites

data.list[0, 1, 2 ]

That doesn't work, if you want 3 items you get them individually.

If I list [0] or [3] etc. in data.list below and print the "arr" variable, I get a temp. If I try a range [0 - 9], I get nothing. If I don't put the [ ] with list, I get error "temp undefined."

It's statements like that which make me think you're guessing. I'm looking directly at the JSON, and I can see that data.list is an array that you need to loop through, and for each item you can access the main.temp property to get the temperature for that time. The timestamp is in the dt property. You don't need to try things to figure out what works and what doesn't, you only need to understand the data structure and then access what you need to access.
for (var i = 0; i < data.list.length; i++) {  console.log(data.list[i].main.temp);}
Are you just unsure about how to access arrays? If you do ar[0 - 9] you are doing subtraction, that is ar[-9]. Array indexing does not support ranges, a list, or whatever else, it's a single index that you are looking up.
Link to comment
Share on other sites

I'm not sure I can guess what you want here.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>JSON Web Service</title><style></style><script>window.onerror = function(a, b, c, d){alert('Javascript Error:n'+a+'nURL: '+b+'nLine: '+c+'  Column: '+d);return true;}</script><script>'use strict';var dobj;function myfunc1(retdata) { dobj = retdata;}window.onload = function(){  document.getElementById("outp1").innerHTML = JSON.stringify(dobj); var str = '<hr/>coord.lat: '+ dobj.coord.lat; str += '<br/>coord.lon: '+ dobj.coord.lon; str += '<br/>sys.message: '+ dobj.sys.message; str += '<br/>sys.country: '+ dobj.sys.country; str += '<br/>sys.sunrise: '+ (new Date(dobj.sys.sunrise*1000)).toString(); str += '<br/>sys.sunset: '+ (new Date(dobj.sys.sunset*1000)).toString(); str += '<br/>main.temp: '+ ((dobj.main.temp - 273.15)*9/5+32).toFixed(3); str += '<br/>main.temp_min: '+ ((dobj.main.temp_min - 273.15)*9/5+32).toFixed(3); str += '<br/>main.temp_max: '+ ((dobj.main.temp_max - 273.15)*9/5+32).toFixed(3); str += '<br/>main.pressure: '+ dobj.main.pressure; str += '<br/>name: '+ dobj.name; document.getElementById("outp2").innerHTML = str;}</script><script src="http://api.openweathermap.org/data/2.5/weather?q=portland,me&callback=myfunc1"></script></head><body><div id="outp1"></div><div id="outp2"></div></body>    </html>
Link to comment
Share on other sites

JSG, thanks, how do I print these temps out in a div?

for (var i = 0; i < data.list.length; i++) {  console.log(data.list[i].main.temp);}

This just gives me last temp:

for (var i = 0; i < data.list.length; i++) { document.getElementById("datadiv").innerHTML = data.city.name + " " + data.list[i].main.temp;

Are you just unsure about how to access arrays? If you do ar[0 - 9] you are doing subtraction, that is ar[-9]. Array indexing does not support ranges, a list, or whatever else, it's a single index that you are looking up.

 

 

Apparently I am unsure as I was trying to access a range in the array.

Edited by paulmo
Link to comment
Share on other sites

You probably should go through the Javascript tutorial at W3Schools.

 

Arrays, loops and assignments are the most basic concepts of programming.

 

The reason only the last element is showing up is because each time you assign something to the innerHTML property you're overwriting what was there before.

Link to comment
Share on other sites

Well, you are going to have to figure out how to interpret the data in the JSON structure. I don't think the temperatures can be Kelvin because my conversion is producing values that seem bogus for Portland OR.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>JSON Web Service</title><style>table,th,td{border:1px solid #bbb;}td,th{text-align:center;padding:0 5px;}</style><script>window.onerror = function(a, b, c, d){alert('Javascript Error:n'+a+'nURL: '+b+'nLine: '+c+'  Column: '+d);return true;}</script><script>'use strict';var f;function myfunc1(retdata) { f = retdata;}window.onload = function(){  document.getElementById("outp2").innerHTML = JSON.stringify(f);  var str = '<table><tr><th>Item</th><th>Date</th><th>Temp</th><th>Temp_Min</th><th>Temp_Max</th><th>Temp_Kf</th></tr>';  for (var i=0,len=f.list.length ; i<len ; i++){    str += '<tr><td>'+i+'</td><td>'+((new Date(1000*f.list[i].dt))).toDateString() +'</td>';    str += '</td><td>'+((f.list[i].main.temp - 273.15)*(9/5)+32).toFixed(3)+'</td>';    str += '<td>'+((f.list[i].main.temp_min - 273.15)*(9/5)+32).toFixed(3)+'</td>';    str += '<td>'+((f.list[i].main.temp_max - 273.15)*(9/5)+32).toFixed(3)+'</td>';    str += '<td>'+ (f.list[i].main.temp_kf) +'</td></tr>';  }  str += '</table>';  document.getElementById("outp1").innerHTML = str;}</script><script src="http://api.openweathermap.org/data/2.5/forecast?q=portland,me&callback=myfunc1"></script></head><body><h2>Temperature Array:</h2><div id="outp1"></div><hr/><h2>Raw JSON Data:</h2><div id="outp2"></div></body>       </html>
Link to comment
Share on other sites

I would recommend using a loop to store all of the text you're building in a variable, then after the loop print that variable into the div.

Thanks, this seems like a loop, so how to build in variable and print loop?

for (var i = 0; i < data.list.length; i++) { document.getElementById("datadiv").innerHTML = data.city.name + " " + data.list[i].main.temp;
Edited by paulmo
Link to comment
Share on other sites

Nice tables Dave, thank you! The conversions are a good reference. Yes this API does not seem to produce accurate readings even though it is highly regarded. :Unsure: I'm in portland, me (not oregon)

 

I don't think the temperatures can be Kelvin because my conversion is producing values that seem bogus for Portland OR.

Edited by paulmo
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...