如何使用此网站API将字典组织成列表?

问题描述:

对于一个项目我使用这个网站的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

任何人都可以帮助我正确地组织这些词典吗?我认为问题在于我将整行添加到列表的每个元素中。

在这种情况下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