[英]How to extract specific value from json data that is now a dictionary
我正在開發一種工具,可以從我的公司 CRM 工具中下載未結案例列表。 我有將它們拉下來並放入文件的代碼。 文件格式為:
{
"result": [
{
"active":"true",
"number":"case_123",
"state":"Open",
"customer":"",
"priority":"3 - Moderate",
"assigned_to":"me",
"product":"My Product",
"contact_time_zone":"",
"opened_at":"23/07/2020 11:10:08",
"closed_at":""
},
"<more cases>"
],
}
我想提取鍵“數字”的所有值。
當您輸入帖子主題時,我嘗試遵循給出的一些建議。 這似乎很接近: 如何從 JSON 中提取特定數據?
但沒有奏效。
這是代碼:
import json
print("Started Reading JSON file")
with open("sn_data.json", "r", encoding='utf-8') as read_file:
print("Converting JSON encoded data into Python dictionary")
developer = json.load(read_file)
print(developer['result']['number'])
這會拋出: print(developer['result']['number']) TypeError: list indices must be integers or slices, not str
我已經確認我有一本使用 print(type(developer)) 的字典。
如果我注釋掉上面的打印並使用:
for number in developer.items():
print(developer.items["number"])
我得到: print(developer.items["number"]) TypeError: 'builtin_function_or_method' object is not subscriptable
我查找錯誤並沒有找到真正的答案。 由於我不是一名全職 Python 開發人員,所以只支持試圖提供幫助的人。
字典中“結果”鍵的值是一個列表,因此您不能使用 ['number'] 對其進行索引。 'number' 是該列表中字典中的鍵。
結果: [{}。{}...]
所以你必須迭代它。 該列表中的每個項目都是一個字典,因此您可以使用 ['result'] 對其進行迭代
for result in developer['result']:
print(result['number'])
在您的第二個代碼塊中,您將一個值存儲在一個名為number的變量中,然后您使用一個字符串“number”來訪問它。 僅供參考,這不是一回事。 盡管如此, dict.items() 將返回一個列表,您也不能像 dict 一樣訪問它。
您應該使用developer['result'][0]['number']
。 您的變量Developer
是一個字典和您想要的鍵, result
是 1 個元素的列表(如我們所見),因此您必須首先引用字典鍵( developer
)然后是索引( 0
或任何它是)然后是另一個字典的鍵number
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.