转换tweepy JSON对象为字典

问题描述:

我想将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

好吧,这应该做到这一点!它甚至被测试(感谢张贴额外的信息)。

>>> 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关键你有兴趣的名单。

将这样的事情对你的工作?

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

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

要将Tweepy '状态' 对象转换为一个Python字典(JSON),在对象上访问私有成员 “_json”。

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