You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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'。

解决步骤

  1. 先排查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'。

  2. 修正代码提取鞋子数组
    根据实际的结构,调整代码路径:

    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:47:32