json and blogger

Today I decided to learn about json. To help me with this I coded a little python script I call blogger-updates.py. It takes the name of a blogger blog and optionally a number designating the number of entries to reterieve. I used Google’s blogger api to get the data.

*** Updated to account for non numeric input when setting max entries.

import simplejson
import sys
import urllib2

def usage():
    print sys.argv[0], 'blogname [max-results]'
    print '    Gets blog updates from blogger.com'

if len(sys.argv)  3:
    usage()
    sys.exit(2)

try:
    blogname = sys.argv[1]
except:
    print "Sorry:", sys.exec_type, ":", sys.exec_value
    sys.exit(1)

max_results = 5

if len(sys.argv) is 3:
    try:
        max_results = int(sys.argv[2])
    except:
        pass

try:
    json_data = simplejson.load(urllib2.urlopen('http://%s.blogspot.com/feeds/posts/default?alt=json&orderby=published&sortorder=ascending&max-results=%i' % (blogname, max_results)))
except:
    print "Sorry:", sys.exc_type, ":", sys.exc_value
    sys.exit(1)

for entry in json_data['feed']['entry']:
    print 'Title: %s' % (entry['title']['$t'])
    print 'Author: %s' % (entry['author'][0]['name']['$t'])
    print 'Published: %s' % (entry['published']['$t'])
    print 'Content: %s' % (entry['content']['$t'])
    print ''