This tumblelog is further embellished by my Flickr, Twitter, and Digg accounts.

17 Feb 08

Using Yahoo! Pipes to turn XML into JSON (with a callback)

I had another obstacle to overcome this weekend while working on the suite of 2041.com’s “minisites”, and this time I found my solution in Yahoo! Pipes. I was tasked with embedding a weather forecast for Bellingshausen, Antarctica onto the soon-to-launch E-Base minisite.

There is an XML Feed for Bellingshausen’s weather via the Weather Underground, so I was off to a good start. I wanted to accomplish this task with Javascript, so that if the feed was slow to respond it wouldn’t prevent the rest of the HTML page from loading. In fact this was the same solution we used to embed Robert Swan’s twitter feed onto the homepage of the main 2041.com site.

Using Yahoo! Pipes, this turned out to a breeze. Here is what Yahoo! Pipes did for me:

  1. Fetch XML feed for Bellingshausen weather
  2. Cache the response on the Yahoo! server
  3. Convert the XML into JSON
  4. Return the JSON response, passing it to a callback function that I define

At step 4 is where I pick up and finish off the job. I simply define the callback function, and program it to extract the info I need, and update the DOM with that info.

Here’s what my source code look like:

<script type="text/javascript">
        function myCallback(jsonData)
        {
            // update the DOM here
        }
    </script>
    <script src="http://pipes.yahoo.com/pipes/pipe.run?_id=4HBwnV3d3BGriMJbnkartA&_render=json&_callback=myCallback" type="text/javascript"></script>

The real clever bits are at the last line, when we call the actual pipe I’ve created. If you look at the end of the url, you’ll see two parameters passed:

  • _render=json: This tells Yahoo! Pipes to return the response as JSON
  • _callback=myCallback: Here it wraps the JSON in a function call to myCallback() (which I’ve defined in the lines above)
Comments (View)