2015-05-09 29 views
0

對於一個項目我使用這個網站的API:如何使用此網站API將字典組織成列表?

http://api.mapmyuser.com/userinfo.php?site=google.com&output=json 

我有困難的類型的字典分離成一個列表。這是我的項目到目前爲止的代碼:

import json 

import urllib.request 

import statistics 

    def get_website_stats(website): 
    url = 'http://api.mapmyuser.com/userinfo.php?site='+ website +'&output=json' 
    lines = urllib.request.urlopen(url).readlines() 
    list_of_strings = [] 
    for obj in lines: 
     list_of_strings.append(obj.decode('utf-8').strip('\n')) 
    merged_string = ' ' 
    for string in list_of_strings: 
     if string not in ('[', ']'): 
      merged_string += string 
    return json.loads(merged_string) 

    symbol=input("What is the website name? (Do not include www)") 
    stats = get_website_stats(symbol) 
    print(stats['bro']) 

如果通過API讀取很明顯我想打印出該網站的用戶正在使用的瀏覽器,而是我得到一個錯誤:

TypeError: list indices must be integers, not str

任何人都可以幫助我正確地組織這些詞典嗎?我認爲問題在於我將整行添加到列表的每個元素中。

回答

1

在這種情況下stats是一個列表。

print(stats[0]['bro']) 

也在這裏是你的腳本的一個較短的版本:

import requests 
url = 'http://api.mapmyuser.com/userinfo.php?site=www.google.com&output=json' 
r = requests.get(url) 
if r.ok: 
    stats = r.json() 
    if stats: 
     print(stats[0]['bro']) # 1st entry 
    for s in stats: 
     print s['bro'] 
+1

如果你正在使用'requests'你應該簡化與'requests.get'參數的有效載荷的URL。 – Hooked