开发者

How to work with multiple JSON formats?

I'm playing with a python script to pull, parse and format Twitter trend JSON. The location specific format nests the trends inside of an array:

[
  {
    "created_at": "2010-07-15T22:31:11Z",
    "trends": [
      {
        "name": "trendy",
        "url": "http://search.twitter.com/search?q=trendy",
        "query": "trendy"
      }, ...

While the daily and weekly json formats do not:

开发者_C百科
{
  "trends": {
    "2011-01-14 15:20": [
      {
        "name": "#trendy",
        "events": null,
        "promoted_content": null,
        "query": "#trendy"
      },

I'm using this python to list the trends:

class trend:
        #initialize a "trend" object with foo = trend(query,name ...)
        def __init__(self, query, name, promoted_content, events, url):
                self.query = query
                self.name = name
                self.promoted_content = promoted_content
                self.events = events
                self.url = url 

class trending:
        def __init__(self,api_url,title):
                self.api_url = api_url
                self.title = title

        def get_trending(self):
                import simplejson as json
                import urllib2

                trends_all = json.loads(urllib2.urlopen(self.api_url).read())
                return trends_all

        def list_trending(self):
                trends_all = self.get_trending()
                print "%s\n" % self.title

                for x in trends_all[0]['trends']:
                    thistrend = trend(x['query'], x['name'], x['promoted_content'], x['events'], x['url'])
                    print "\t %s (%s) %s" %(thistrend.name, thistrend.url, thistrend.promoted_content)

This works for the location formats (the first) but not the daily/weekly formats. So I'm wondering if there's a smart way to distinguish the two JSON structures and re-structure them so I can work with both.


The more generic case is the one with the list. Since you need only the first element, if the parsed object is a list, you extract the first value.

In your code, you can simply replace:

for x in trends_all[0]['trends']:
    ...

with

if isinstance(trends_all, list):
    trends_all = trends_all[0]
for x in trends_all['trends']:
    ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜