这是我的python脚本:
import json
with open('JSON_DataProvider.json', 'r') as file:
json_dict = json.load(file)
print (json_dict["office"][0]["medical"][0]["price"])
运行代码后出现以下错误
Traceback (most recent call last):
File "D:/Project/@Python/open_json.py", line 7, in <module>
print (json_dict["office"][0]["medical"][0]["price"])
KeyError: 0
这里是我使用的json数据:
{ "office":
{"medical": [
{ "room-number": 100,
"use": "reception",
"sq-ft": 50,
"price": 75
},
{ "room-number": 101,
"use": "waiting",
"sq-ft": 250,
"price": 75
},
{ "room-number": 102,
"use": "examination",
"sq-ft": 125,
"price": 150
},
{ "room-number": 103,
"use": "examination",
"sq-ft": 125,
"price": 150
},
{ "room-number": 104,
"use": "office",
"sq-ft": 150,
"price": 100
}
]},
"parking": {
"location": "premium",
"style": "covered",
"price": 750
}
}
请帮我找出哪里做错了?你知道吗
因为我试图从json文件中获取数据,并输入我们的测试自动化脚本,这就是嵌套的json数据提供者。你知道吗
正在引发异常,因为您正尝试访问具有索引的词典项。而不是
json_dict["office"][0]["medical"][0]["price"]
尝试json_dict["office"]["medical"][0]["price"]
,这应该是可行的。我希望这有帮助。你知道吗改变
至
在尝试打印出
json_dict
之后,我们可以找到问题所在。你知道吗{'office': {'medical': [{'room-number': 100, 'use': 'reception', 'sq-ft': 50, 'price': 75}, {'room-number': 101, 'use': 'waiting', 'sq-ft': 250, 'price': 75}, {'room-number': 102, 'use': 'examination', 'sq-ft': 125, 'price': 150}, {'room-number': 103, 'use': 'examination', 'sq-ft': 125, 'price': 150}, {'room-number': 104, 'use': 'office', 'sq-ft': 150, 'price': 100}]}, 'parking': {'location': 'premium', 'style': 'covered', 'price': 750}}
正确的方法是:
json_dict["office"]["medical"][0]["price"]
希望有帮助!你知道吗
相关问题 更多 >
编程相关推荐