simplejson.loads usage
I want to display a random link + its name from an RSS feed. The code I use is:
def updateFeed(url):
query_args = { 'q': 'http://news.google.com/?output=rss', 'v':'1.0', 'num': '15', 'output': 'json' }
qs = urllib.urlencode(query_args)
loader = 'http://ajax.googleapis.com/ajax/services/feed/load'
loadurl = '%s?%s' % (loader, qs)
logging.info(loadurl)
result = urlfetch.fetch(url=loadurl,
headers={'Referer': '...'})
if result.status_code == 200:
news = simplejson.loads(result.content)
I do get response data in JSON but I don't know how to randomly select an item. Can you please advice?
{u'responseData': {u'feed': {u'feedUrl': u'http://news.google.com/?output=rss', u'description': u'Google News', u'author': u'', u'title': u'Top Stories - Google News', u'link': u'http://news.google.com/news?pz=1&jfkl=true&ned=us&hl=en', u'entries': [{u'publishedDate': u'Tue, 02 Aug 2011 08:51:09 -0700', u'title': u'House Approved Debt Bill Faces Final Hurdle - NY1', u'author': u'', u'content': u'<table border="0" cellpadding="2" cellspacing="7" style="vertical-align:top"><tr><td width="80" align="center" valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><a href="http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNEyXr4E-W9lA8bsV4_Zslubxd-6_g&url=http://www.theglobeandmail.com/news/world/americas/little-sign-of-compromise-ahead-of-us-default-deadline/article2114420/"><img src="http://nt3.ggpht.com/news/tbn/dyFy2sz6rKRlJM/6.jpg" alt="" border="1" width="80" height="80"><br><font size="-2">Globe and Mail</font></a></font></td><td valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><br><div style="padding-top:0.8em"><img alt="" height="1" width="1"></div><div><a
Edit: It works now almost perfect and I learn about JSON doing this:
def updateFeed(url):
query_args = { 'q': 'http://news.google.com/?output=rss', 'v':'1.0', 'num': '15', 'output': 'json' }
qs = urllib.urlencode(query_args)
loader = 'http://ajax.googleapis.com/ajax/services/feed/load'
loadurl = '%s?%s' % (loader, qs)
logging.info(loadurl)
result = urlfetch.fetch(url=loadurl,headers={'Referer': '...'})
if result.status_code == 200:
news = simplejson.loads(result.content)
""" not working, using random.randrange instead
some_key = random.choice(news.keys())
开发者_C百科 something = news[some_key]
"""
i = random.randrange(0,10)#to do: instead of 10, it should be number of entries
title = news[u'responseData'][u'feed'][u'entries'][i][u'title']
link = news[u'responseData'][u'feed'][u'entries'][i][u'link']
return mark_safe('<a href="%s">%s</a>' % (link, title))
When you load JSON in Python, it's converted into (nested) dicts and lists. { ... }
objects become dictionaries, and [ ... ]
comma-separated items become lists.
For example, to get the feed URL, you can do:
feedUrl = news[u'responseData'][u'feed'][u'feedUrl']
To select a random element from a dictionary, you can do:
import random
some_key = random.choice(news.keys())
something = news[some_key]
精彩评论