在python中将json列表转换为字典

时间:2017-02-14 04:23:39

标签: python json api dictionary

我使用的数据是Twitter API的推特热门话题。

url_0 = 'https://api.twitter.com/1.1/trends/place.json?id=2459115'  
res = requests.get(url_0, auth=auth)  

print(res, res.status_code, res.headers['content-type'])  
print(res.url)

top_trends_twitter = res.json()  
data= top_trends_twitter[0]  

这就是数据的样子:

[{'as_of': '2017-02-13T21:59:32Z',  
  'created_at': '2017-02-13T21:53:22Z',  
  'locations': [{'name': 'New York', 'woeid': 2459115}],  
  'trends': [{'name': 'Victor Cruz',  
    'promoted_content': None,  
    'query': '%22Victor+Cruz%22',  
    'tweet_volume': 45690,  
    'url': 'http://twitter.com/search?q=%22Victor+Cruz%22'},  
   {'name': '#percussion',  
    'promoted_content': None,  
    'query': '%23percussion',  
    'tweet_volume': None,  
    'url': 'http://twitter.com/search?q=%23percussion'},  .....etc

现在,在我使用SQL连接服务器并创建数据库和表之后,会出现错误。这是导致我麻烦的部分:

for entry in data:  
    trendname = entry['trends']['name']  
    url = entry['trends']['url']  
    num_tweets = entry['trends']['trend_volume']  
    date= entry['as_of']  
    print("Inserting trend", trendname, "at", url)  
    query_parameters = (trendname, url, num_tweets, date)  
    cursor.execute(query_template, query_parameters) 



con.commit()  
cursor.close()  

然后,我收到了这个错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-112-da3e17aadce0> in <module>()  
     29   
     30 for entry in data:  
---> 31     trendname = entry['trends']['name']  
     32     url = entry['trends']['url']  
     33     num_tweets = entry['trends']['trend_volume']  

TypeError:字符串索引必须是整数

如何将字符串集合转换为字典,以便我可以将其用于输入数据代码?

1 个答案:

答案 0 :(得分:2)

您需要entry['trends'][0]['name']entry['trends']是一个列表,您需要整数索引才能访问列表项。

尝试如下:

data=[{'as_of': '2017-02-13T21:59:32Z',  
  'created_at': '2017-02-13T21:53:22Z',  
  'locations': [{'name': 'New York', 'woeid': 2459115}],  
  'trends': [{'name': 'Victor Cruz',  
    'promoted_content': None,  
    'query': '%22Victor+Cruz%22',  
    'tweet_volume': 45690,  
    'url': 'http://twitter.com/search?q=%22Victor+Cruz%22'},  
   {'name': '#percussion',  
    'promoted_content': None,  
    'query': '%23percussion',  
    'tweet_volume': None,  
    'url': 'http://twitter.com/search?q=%23percussion'}]}]

for entry in data:
    date= entry['as_of']
    for trend in entry['trends']:
        trendname = trend['name']  
        url = trend['url']  
        num_tweets = trend['tweet_volume']  
        print trendname, url, num_tweets, date

输出:

Victor Cruz http://twitter.com/search?q=%22Victor+Cruz%22 45690 2017-02-13T21:59:32Z
#percussion http://twitter.com/search?q=%23percussion None 2017-02-13T21:59:32Z