将 tweepy JSON 对象转换为 dict [英] Convert tweepy JSON object to dict
问题描述
我想将 Tweepy api.trends_location(woeid)
调用的结果转换为 dict(或 dict 的 dict),以便我可以使用这些值(真的,我想要以名称"值的字典结束).Tweepy 文档说结果是一个 JSON 对象"(见此处),但是当我检索它时,type(retrieved)
的计算结果为 list
.果然,retrieved
的 len
为 1,retrieved[0]
给了我一个项目:[{'trends': [{'url': 'http://search.twitter.com/search?q=%23questionsidontlike', 'query': '%23questionsidontlike', 'events': None, 'Promotion_content': None, 'name': '#questionsidontlike'}, ], (更多相同), 'created_at': '2011-01-31T22:39:16Z', 'as_of': '2011-01-31T22:47:47Z', 'locations': [{'woeid': 23424977, 'name': 'United States'}]}]
.
我可以调用 json.dumps
,它会给出一个格式很好的表示,但这对我来说没什么用,json.loads
给了我:__init__() 得到了一个意外的关键字参数 'sort_keys'
我应该如何进行?
完整代码链接:https://gist.github.com/805129
好的,应该可以了!它甚至已经过测试(感谢您发布附加信息).
<预><代码>>>>名称 = [trend["name"] 检索趋势 [0]["trends"]]>>>名字['#wishuwould'、'#questionsidontlike'、'#februarywish'、'Purp &赞助人"、埃及人"、酷赫尔克"、美国派"、文森法官"、尤里卡·纳特"、埃迪·豪斯"]我认为大部分混淆来自将输出称为 JSON 对象的文档,这与需要使用 json
模块转换的 JSON 字符串不同.
这是如何工作的:retrieved
是一个包含单个项目的列表,它是包含 trends
键的字典,所以 retrieved[0]["trends"]
是趋势词典的列表,其中每个趋势词典都包含你感兴趣的name
键.
I'd like to convert the result of a Tweepy api.trends_location(woeid)
call to a dict (or a dict of dicts), so I can work with the values (really, I want to end up with a dict of the 'name' values). The Tweepy documentation says that the result is 'a JSON object' (see here), but when I retrieve it, type(retrieved)
evaluates to list
. Sure enough, retrieved
has a len
of 1, and retrieved[0]
gives me a single item:
[{'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'}]}]
.
I can call json.dumps
, which will give a nicely-formatted representation, but that's not much use to me, and json.loads
gives me: __init__() got an unexpected keyword argument 'sort_keys'
How should I proceed?
Link to full code: https://gist.github.com/805129
Okay this should do it! It is even tested (thanks for posting the additional info).
>>> 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']
I think most of the confusion came from the documentation referring to the output as a JSON object, which is different than a JSON string which would need to be converted using the json
module.
How this works: retrieved
is a list that contains a single item, which is the dictionary that contains the trends
key, so retrieved[0]["trends"]
is the list of trend dictionaries, where each trend dictionary contains the name
key you are interested in.
这篇关于将 tweepy JSON 对象转换为 dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!