Python解析Supreme网站JSON数据时遭遇KeyError: 'Shoes'问题求助
解决Supreme JSON解析中的KeyError: 'Shoes'问题
Hey there, let's break down why you're getting that frustrating KeyError and fix it up!
问题回顾
你尝试解析Supreme的mobile_stock.json数据,想提取'Shoes'数组,但运行这段代码时触发了KeyError:
import urllib.request, json with urllib.request.urlopen("https://www.supremenewyork.com/mobile_stock.json") as url: data = json.loads(url.read().decode()) print(type(data['Shoes']))
错误信息:
Traceback (most recent call last):
File "C:\Users-\PycharmProjects-\test.py", line 7, in
print(type(data['Shoes']))
KeyError: 'Shoes'
原因分析
这个错误的核心是:你要找的'Shoes'键根本不存在于JSON的顶级结构里。实际的Supreme库存JSON结构是嵌套的,鞋子分类的数据藏在子字典里,而且键名是全小写的'shoes',不是大写的'Shoes'。
解决步骤
先排查JSON结构
先打印出数据的顶级键,搞清楚数据的层级:import urllib.request, json from pprint import pprint with urllib.request.urlopen("https://www.supremenewyork.com/mobile_stock.json") as url: data = json.loads(url.read().decode()) # 查看所有顶级键 print("顶级键列表:", data.keys()) # 格式化打印完整结构,方便查看嵌套关系 pprint(data)运行后你会发现,顶级键里有
'products_and_categories',鞋子数据就藏在这个键对应的字典里,键名为'shoes'。修正代码提取鞋子数组
根据实际的结构,调整代码路径:import urllib.request, json with urllib.request.urlopen("https://www.supremenewyork.com/mobile_stock.json") as url: data = json.loads(url.read().decode()) # 正确提取鞋子数组 shoes_array = data['products_and_categories']['shoes'] print(type(shoes_array)) # 会输出<class 'list'>,就是你要的数组 # 如果想查看具体内容,可以打印出来 # print(shoes_array)
这样就能成功获取到鞋子分类的数组了!
内容的提问来源于stack exchange,提问作者programming_for_fun
相关产品推荐
相关产品推荐

