simplejson.loads用法

时间:2011-08-02 16:21:14

标签: python json rss simplejson

我想在RSS Feed中显示随机链接+名称。 我使用的代码是:

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) 

我在JSON中获得响应数据,但我不知道如何随机选择项目。能告诉你吗?

{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&amp;jfkl=true&amp;ned=us&amp;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&amp;fd=R&amp;usg=AFQjCNEyXr4E-W9lA8bsV4_Zslubxd-6_g&amp;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 

编辑:它现在几乎完美无缺,我了解JSON这样做:

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())
        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))

1 个答案:

答案 0 :(得分:3)

在Python中加载JSON时,它会转换为(嵌套的)dicts和列表。 { ... }个对象成为字典,[ ... ]逗号分隔的项目成为列表。

例如,要获取Feed网址,您可以执行以下操作:

feedUrl = news[u'responseData'][u'feed'][u'feedUrl']

要从字典中选择随机元素,您可以执行以下操作:

import random
some_key = random.choice(news.keys())
something = news[some_key]