2011-01-31 112 views
3

我想將Tweepy api.trends_location(woeid)調用的結果轉換爲字典(或字典的字典),所以我可以使用這些值(真的,我想結束一個「名稱」值的字典)。 Tweepy文檔說結果是'JSON對象'(see here),但是當我檢索它時,type(retrieved)的計算結果爲list。果然,retrieved有一個len的1,和retrieved[0]給我一個單一的項目:
[{'trends': [{'url': 'http://search.twitter.com/search?q=%23questionsidontlike', 'query': '%23questionsidontlike', 'events': None, 'promoted_content': None, 'name': '#questionsidontlike'}, ], (more of the same), 'created_at': '2011-01-31T22:39:16Z', 'as_of': '2011-01-31T22:47:47Z', 'locations': [{'woeid': 23424977, 'name': 'United States'}]}]轉換tweepy JSON對象爲字典

我可以叫json.dumps,這將給一個很好的格式表示,但這是沒多大用的我,json.loads給我:__init__() got an unexpected keyword argument 'sort_keys'

我應該如何進行?

鏈接到全碼:https://gist.github.com/805129

+0

Python中的JSON對象實際上是用`list`和`dict`對象表示的。 `dict`用於對象,`list'用於數組。你究竟想要做什麼? – thkala 2011-01-31 23:21:05

+0

我明白,但是一個成員的列表,這是整個結果沒有太大的用處,在這種情況下。我想將'name'的值提取到他們自己的列表中。 – urschrei 2011-01-31 23:28:23

回答

2

好吧,這應該做到這一點!它甚至被測試(感謝張貼額外的信息)。

>>> names = [trend["name"] for trend in retrieved[0]["trends"]] 
>>> names 
['#wishuwould', '#questionsidontlike', '#februarywish', 'Purp & Patron', 'Egyptians', 'Kool Herc', 'American Pie', 'Judge Vinson', 'Eureka Nutt', 'Eddie House'] 

我想大多數的混亂的來自文檔參照輸出作爲JSON對象,這是比這將需要使用json模塊被轉換JSON字符串不同。

如何工作的:retrieved是包含一個項目,這是一個包含trends鍵字典的清單,讓retrieved[0]["trends"]是趨勢字典,其中每個趨勢詞典包含name關鍵你有興趣的名單。

2

將這樣的事情對你的工作?

def searchKeys(struct, keys, result = None, recursive = True): 
     if result is None: 
       result = [] 

     if isinstance(struct, dict): 
       for k in keys: 
         if struct.has_key(k): 
           result.append(struct[k]) 

       if recursive: 
         for i in struct.values(): 
           searchKeys(struct = i, keys = keys, result = result, recursive = recursive) 
     elif isinstance(struct, list): 
       if recursive: 
         for i in struct: 
           searchKeys(struct = i, keys = keys, result = result, recursive = recursive) 

     return result 

用例:

>>> searchKeys(struct = a, keys = ['name']) 
['United States', '#questionsidontlike'] 

它遞歸走下一個dict/list層次結構搜索一組dict密鑰,並存儲相應的值到一個list

0
>>> import simplejson 
>>> a = {"response":[{"message":"ok"},{"message":"fail"}]} 
>>> json = simplejson.dumps(a) 
>>> simplejson.loads(json) 
{'response': [{'message': 'ok'}, {'message': 'fail'}]} 

http://docs.python.org/library/json.html

1

要將Tweepy '狀態' 對象轉換爲一個Python字典(JSON),在對象上訪問私有成員 「_json」。

tweets = tweepy_api.user_timeline(screen_name='seanharr11') 
json_tweets = map(lambda t: t._json, tweets)