0

I am using the wunderground API to practice my JS and have a question regarding how to parse the JSON response(s) they are returning when I make calls.

I have a simple function below where I am making a call to the URL and receiving the response and sending it to an iframe. In the iframe I am seeing the raw JSON. What I want to know is how can I parse the JSON and display the parsed information in the iframe. ( or a div if more simple)

I am assuming it is some variation of JSON.parse but I havent been able to get it to work the way that I want.

Also I prefer to avoid jquery I would like to use regular JS.

  function conditions(){
    var zip = document.getElementById("zip").value;
    var url = "http://api.wunderground.com/api/<API_KEY>/conditions/q/" + zip + ".json"
    {
    window.open(url,"frame");
    }

UPDATE: This is what I have now. I know I am implementing this wrong. I also am still running into the same origin issue and had to bypass Chromes security for testing. Any suggestions are appreciated.

function conditions() {

GET_JSON = function(callback){
var c = document.getElementById("zip").value;
var x = new String("http://api.wunderground.com/api/KEY/conditions/q/" + c + ".json" +"?callback=JSONCallback");
    var req = new XMLHttpRequest();
    req.open("GET", x, true);
    req.onreadystatechange = function(){
        if(this.readyState==4){
            callback(JSON.parse(req.responseText));
        }
    }
    req.send(null);
}
JSONCallback = function(JSONObj){
    alert(JSONObj);
};
GET_JSON(JSONCallback);
}
steelthunder
  • 438
  • 2
  • 12
  • 27
  • 1
    You do not request JSON with window.open or an iframe. You would need to use the XMLHttpRequest object and hopefully they support CORS because of the same origin policy. If not, hopefully they support JSONP. – epascarello Jan 15 '14 at 18:31
  • 1
    You need to use AJAX, and in the `onreadystatechange` function call `JSON.parse` and write what you want into the new window. You may not be able to do this because of the AJAX same-origin policy, so you may need to use a proxy function on your server. – Barmar Jan 15 '14 at 18:31
  • Why are you using an iFrame to do this instead of an AJAX call? Are you sure their API allows cross-domain requests? If they don't then you'll need to use a proxy script on your server. – gen_Eric Jan 15 '14 at 18:31
  • check my answer out, I think it's all you need to deal with this issue. – Mehran Hatami Jan 15 '14 at 22:27

2 Answers2

0

No idea if wunderground uses the same sort of API as wiki media. However, here is an example of how you would perform JSONP(read about it here: JSONP) which will let you query a page in spite of cross domain requests.

If you read this question: Trying to search wunderground locations with javascript, jquery, and html, you can see that JSONP is suggested. As such, a small modification to the following example will get you started on what you need to do to get your results from the site.

<!DOCTYPE html>
<html>
   <head>
      <title>Wikipedia JSON Grabber</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <style>
         div{
            position: relative;
            background-color: white;
         }
      </style>
      <script>
         // Function call the Wikipedia API
         function doFetch() {
            var tmpScript = document.createElement("script");
            tmpScript.src = "http://en.wikipedia.org/w/api.php?" +
                    "format=json" +
                    "&callback=gotFetch" +
                    "&action=query" +
                    "&titles=json" +
                    "&prop=revisions" +
                    "&rvprop=content";
            document.body.appendChild(tmpScript);
         }

         // Callback to trigger whenever the API responds
         function gotFetch(data) {
            var parent = document.createElement("div"),
                    depth = 0;
            document.body.appendChild(parent);
            console.log("Got data");
            for (var t in data) {
               console.log(data[t]);
               printData(data, parent, depth);
            }
         }

         // Recursively print out the object received to console
         function printData(data, parent, depth) {
            for (var prop in data) {

               var newDiv = document.createElement("div");
               newDiv.style.left = (10 * (depth++)) + "px";
               parent.appendChild(newDiv);

               if (typeof data[prop] === "object") {
                  newDiv.innerHTML = prop;
                  printData(data[prop], newDiv, depth);
               } else {
                  newDiv.innerHTML = data[prop];
               }
            }
         }

         function main() {
            doFetch();
         }
      </script>
   </head>
   <body onload="main();">
      <div></div>
   </body>
</html>
Community
  • 1
  • 1
zero298
  • 25,467
  • 10
  • 75
  • 100
0

I got a sample json url from the wunderground:

var url = "http://api.wunderground.com/api/<API_KEY>/conditions/q/CA/San_Francisco.json";

which its output json is:

{"response":{"version":"0.1","termsofService":"http://www.wunderground.com/weather/api/d/terms.html","features":{"conditions":1}},"current_observation":{"image":{"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png","title":"Weather Underground","link":"http://www.wunderground.com"},"display_location":{"full":"San Francisco, CA","city":"San Francisco","state":"CA","state_name":"California","country":"US","country_iso3166":"US","zip":"94101","magic":"1","wmo":"99999","latitude":"37.77500916","longitude":"-122.41825867","elevation":"47.00000000"},"observation_location":{"full":"SOMA - Near Van Ness, San Francisco, California","city":"SOMA - Near Van Ness, San Francisco","state":"California","country":"US","country_iso3166":"US","latitude":"37.773285","longitude":"-122.417725","elevation":"49 ft"},"estimated":{},"station_id":"KCASANFR58","observation_time":"Last Updated on January 15, 12:12 PM PST","observation_time_rfc822":"Wed, 15 Jan 2014 12:12:06 -0800","observation_epoch":"1389816726","local_time_rfc822":"Wed, 15 Jan 2014 12:12:10 -0800","local_epoch":"1389816730","local_tz_short":"PST","local_tz_long":"America/Los_Angeles","local_tz_offset":"-0800","weather":"Partly Cloudy","temperature_string":"69.8 F (21.0 C)","temp_f":69.8,"temp_c":21.0,"relative_humidity":"28%","wind_string":"From the WNW at 2.0 MPH","wind_dir":"WNW","wind_degrees":295,"wind_mph":2.0,"wind_gust_mph":0,"wind_kph":3.2,"wind_gust_kph":0,"pressure_mb":"1026","pressure_in":"30.29","pressure_trend":"-","dewpoint_string":"35 F (2 C)","dewpoint_f":35,"dewpoint_c":2,"heat_index_string":"NA","heat_index_f":"NA","heat_index_c":"NA","windchill_string":"NA","windchill_f":"NA","windchill_c":"NA","feelslike_string":"69.8 F (21.0 C)","feelslike_f":"69.8","feelslike_c":"21.0","visibility_mi":"10.0","visibility_km":"16.1","solarradiation":"--","UV":"3","precip_1hr_string":"0.00 in ( 0 mm)","precip_1hr_in":"0.00","precip_1hr_metric":" 0","precip_today_string":"0.00 in (0 mm)","precip_today_in":"0.00","precip_today_metric":"0","icon":"partlycloudy","icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif","forecast_url":"http://www.wunderground.com/US/CA/San_Francisco.html","history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR58","ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=37.773285,-122.417725"}}

so now how are we suppose to get this output!? we have 2 different solution:

1- the old solution is using ajax to get the json as a string and then parse it as an object, something like this:

GET_JSON = function(callback){
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.onreadystatechange = function(){
        if(this.readyState==4){
            callback(JSON.parse(req.responseText));
        }
    }
    req.send(null);
}
JSONCallback = function(JSONObj){
    alert(JSONObj);
};
GET_JSON(JSONCallback);

but the problem here is if you do that in your site you would face with this ERROR:

No 'Access-Control-Allow-Origin' header is present on the requested resource.
    Origin 'http://mydomain.com' is therefore not allowed access.

2- No problem, wunderground weather api supports JSONP and it will help us to solve it, we have to just make a JSONP call, the tricky point here is, we won't use the regular ajax solution anymore:

GET_JSON = function(callback){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url + "?callback=" + callback;
    document.body.appendChild(script);
}
window.JSONCallback = function(JSONObj){
    alert(JSONObj);
};
GET_JSON("JSONCallback");

there is a very tricky point that is very important. if you check the last line instead of passing the callback object as a argument, I have passed its name, why is that?

the answer would be, if we want to have a JSONP call we have to pass the callback function's name with callback queryString. like this:

url = "http:// ... .json?callback=JSONCallback";

this was all you need to know to have access to your json object, without you needing to parse the string.

Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
  • Thank you for your effort in attempting to assist me. I however am not sure how to implement what you are suggesting. I updated the script that I have now in the main post. What would I need to fix now? – steelthunder Jan 16 '14 at 18:09
  • you have mixed ajax call and jsonp, in your code if you replace the GET_JSON with my second GET_JSON (without using XmlHttpRequest) your problem is solved. – Mehran Hatami Jan 17 '14 at 12:41