我尝试访问JSON文件中的一些字典中的'gold_spent '键。
下面是我的代码:import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data['gold_spent'])
当我运行这个时,我得到这个"KeyError: 'gold_spent'"我不知道我做错了什么,希望你能帮助我。
您正在查找的数据是嵌套的。见下文.
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
输出46294255
您遇到了一个异常,因为gold_spent
根本不是第一级键,您需要调查结构以找到它。访问字典中不存在的键总是以KeyError异常结束。
import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data.keys())
# dict_keys(['profiles'])
print(json_data['profiles'].keys())
# dict_keys(['590cedda63e145ea98d44015649aba30'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30'].keys())
# dict_keys(['profile_id', 'cute_name', 'current', 'last_save', 'raw', 'items', 'data'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
# 46294255