Tuesday, January 6, 2009

JSON Feed for Blogger

Here is how I created my blog feed on boujin.net.

1) Loaded in jQuery
2) Used the built in .getJSON function

First, I ran into problems getting jQuery working correctly with the feed. I was confused over which function I should use, "load", "getJSON", etc. I finally decided on getJSON as I learned that you cannot do cross domain fetches using a typical XML feed. If you try to do this, you'll get the "access to restricted uri denied jquery" error message when looking at the Javascript errors.

Okay, so I finally got the right function selected, but now I needed to figure out how to get the correct feed from blogger. Well, after going through Feedburner and a lot of other useless methods I came across the blogger blog by Google detailing how to utilize the API to get a JSON feed. I then ended up with the following URL to get the JSON feed from my blog:

http://boujin.blogspot.com/feeds/posts/default?alt=json-in-script&callback=?

Where the "?" gets replaced automatically by jQuery.

As a brief aside, I tried getting the JSON feed from Feedburner at first and followed the rough API they had on their hack page but I could only get a JSON feed that was of no use to me or a blank JSONP feed. Anyone have input on how to get the JSONP feed to work?

Finally I had the JSON feed coming in correctly and now there was just the javascript code to write that would actually parse it and write the HTML to the page. Here is the function that I wrote to do just that:

$(document).ready(function() {
$.getJSON("http://boujin.blogspot.com/feeds/posts/default?alt=json-in-script&callback=?",
function(data){
var html = '';
$.each(data.feed.entry, function(id, item){
var title = item.title.$t;
var summary = item.summary.$t;
var link = item.link[4].href;
html += "<h3><a href='"+link+"'>"+title+"</a></h3><p>"+summary;
html += "<br/><a href='"+link+"'>continued...</a></p>";
if ( id == 2 ) {
$("#blogFeed").html(html);
return false;
}
});
});
});

No comments: