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

Python读取JSON文件触发KeyError:0错误的问题求助

解决JSON解析中的KeyError: 0问题

你的问题很明确——触发KeyError: 0是因为你误解了JSON数据的结构:"office"对应的是一个字典对象,而不是列表(数组),所以用[0]去索引它肯定会报错。

先看你提供的JSON片段结构:

{ "office": {"medical": [ { "room-number": 100, "use": "reception", "sq-ft": 50, "price": ... } ] } }

这里"office"的值是{"medical": [...]},是一个标准的键值对字典,不是可索引的列表,所以不需要用[0]来访问它的子属性。

修正后的代码很简单,只需要去掉office后面的[0]即可:

import json
with open('JSON_DataProvider.json', 'r') as file:
    json_dict = json.load(file)
# 直接通过键名访问office下的medical,再索引列表中的第一个元素
print(json_dict["office"]["medical"][0]["price"])

另外给你一个小技巧:如果以后不确定JSON的层级结构,可以用pprint模块来格式化输出整个字典,这样能更清晰地看到每个节点的类型:

import json
from pprint import pprint
with open('JSON_DataProvider.json', 'r') as file:
    json_dict = json.load(file)
pprint(json_dict)

内容的提问来源于stack exchange,提问作者ranjan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:29:37