我正在努力处理从 API 获得的 json 数据。我已经进入了几个 api url 来获取我的数据,并将其存储在一个空列表中。然后我想去掉所有写着“声誉”的字段,我只对那个数字感兴趣。在这里查看我的代码:
import json
import requests
f = requests.get('my_api_url')
if(f.ok):
data = json.loads(f.content)
url_list = [] #the list stores a number of urls that I want to request data from
for items in data:
url_list.append(items['details_url']) #grab the urls that I want to enter
total_url = [] #stores all data from all urls here
for index in range(len(url_list)):
url = requests.get(url_list[index])
if(url.ok):
url_data = json.loads(url.content)
total_url.append(url_data)
print(json.dumps(total_url, indent=2)) #only want to see if it's working
到目前为止,我很高兴并且可以输入所有网址并获取数据。下一步我会遇到麻烦。上面的代码为我输出了以下 json 数据:
[
[
{
"id": 316,
"name": "storabro",
"url": "https://storabro.net",
"customer": true,
"administrator": false,
"reputation": 568
}
],
[
{
"id": 541,
"name": "sega",
"url": "https://wedonthaveanyyet.com",
"customer": true,
"administrator": false,
"reputation": 45
},
{
"id": 90,
"name": "Villa",
"url": "https://brandvillas.co.uk",
"customer": true,
"administrator": false,
"reputation": 6
}
]
]
但是,我只想打印出声誉,我无法让它工作。如果我在我的代码中使用print(total_url['reputation'])它不起作用并说"TypeError: list indices must be integers or slices, not str",如果我尝试:
for s in total_url:
print(s['reputation'])
我得到相同的类型错误。
感觉好像我已经尝试了所有方法,但在网上找不到任何可以帮助我的答案,但我知道我还有很多东西要学,我的错误对这里的某些人来说是显而易见的。它似乎与我用 Python 完成的其他事情非常相似,但这次我被卡住了。澄清一下,我期望输出类似于:[568, 45, 6]
也许我从一开始就使用了错误的方法来做到这一点,这就是为什么它对我来说并不奏效。10 月份开始使用 Python 编写代码,它对我来说仍然很新,但我想学习。谢谢大家!