0
我正在玩python腳本來拉,解析和格式化Twitter趨勢JSON。位置特定格式巢趨勢的數組裏面:如何使用多種JSON格式?
[
{
"created_at": "2010-07-15T22:31:11Z",
"trends": [
{
"name": "trendy",
"url": "http://search.twitter.com/search?q=trendy",
"query": "trendy"
}, ...
雖然每天和每週的JSON格式不:
{
"trends": {
"2011-01-14 15:20": [
{
"name": "#trendy",
"events": null,
"promoted_content": null,
"query": "#trendy"
},
我使用這條巨蟒列出趨勢:
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)
這適用於位置格式(第一個),但不適用於每日/每週格式。所以我想知道是否有一種巧妙的方法來區分兩個JSON結構並重新構造它們,以便我可以使用這兩種結構。