【问题标题】:TypeError when trying to parse fortnite-api response尝试解析 fortnite-api 响应时出现 TypeError
【发布时间】:2020-09-07 22:25:14
【问题描述】:
我正在尝试获取 fortnite-api 网站数据,并且只获取“表情”下列出的内容
r = requests.get('https://fortnite-api.com/v2/cosmetics/br', headers=headers)
rr = r.json()
for sub_dict in rr['data']:
for image_sub_dict in sub_dict['type']:
for j in image_sub_dict['value']:
print(j)
这导致TypeError: string indices must be integers | Json data
【问题讨论】:
标签:
python
json
dictionary
python-requests
【解决方案1】:
您没有正确解析数据。
for image_sub_dict in sub_dict['type']: 行将返回 'type' 字典的键,而不是值。相反,您可能只想查询 'type' 字典以获取 "emote" 的值。下面是获取所有表情的图标 url 的示例:
import requests
response = requests.get(
'https://fortnite-api.com/v2/cosmetics/br',
headers={'Accept': 'application/json'},
).json()
for entry in response['data']:
kind = entry['type']['value']
if kind == 'emote':
name = entry['name']
icon = entry['images']['icon']
print(f"{name}: {icon}")
输出:
...
Scorecard: https://fortnite-api.com/images/cosmetics/br/eid_scorecard/icon.png
Team Burger: https://fortnite-api.com/images/cosmetics/br/eid_scorecardburger/icon.png
Team Tomato: https://fortnite-api.com/images/cosmetics/br/eid_scorecardtomato/icon.png
Members Only: https://fortnite-api.com/images/cosmetics/br/eid_secrethandshake/icon.png
...
【解决方案2】:
您需要添加一些日志来查看哪个键是错误的。试试:
rr = r.json()
print(rr, type(rr))
for sub_dict in rr['data']:
print(sub_dict, type(sub_dict))
for image_sub_dict in sub_dict['type']:
print(image_sub_dict, type(image_sub_dict))
for j in image_sub_dict['value']:
print(j)