[英]Unable to parse values from a JSON file
這是我的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 dataprovider。
由於嘗試訪問帶索引的字典項而引發異常。 代替json_dict["office"][0]["medical"][0]["price"]
嘗試json_dict["office"]["medical"][0]["price"]
,應該可以。 我希望這有幫助。
更改
print (json_dict["office"][0]["medical"][0]["price"])
至
print(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"]
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.