2011-09-01 3 views
0

나는 트위터 트렌드 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 구조를 구별하고 다시 구조화 할 수있는 스마트 한 방법이 있는지 궁금 해서요.

답변

0

더 일반적인 경우는 목록이있는 경우입니다. 첫 번째 요소 만 필요하므로 구문 분석 된 개체가 목록이면 첫 번째 값을 추출합니다.

코드에서

, 당신은 단순히 대체 할 수

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

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

관련 문제