[英]How to count value occurrences in json response using python?
我有一個如下所示的 json 響應,我想計算corrId
被提及的次數。
{
"result":
{
"corrList":[
{
"corrId":123456,
"title":"sample1",
},
{
"corrId":45678,
"title":"sample2",
},
{
"corrId":987654,
"title":"sample3",
}
],
"find":true
}
}
對於上述,我希望結果是3
我已經嘗試過類似上面的方法,但它會引發錯誤:
r = requests.get(url = HOSTNAME + endpoint, headers = headers, verify=False)
data = json.loads(r.text)
corrList = len(data['corrList'][0]['corrId'])
print (corrList)
我的錯誤:
TypeError: object of type 'int' has no len()
有人可以幫忙嗎? 提前致謝!
您需要實際計算具有該鍵的dict
的數量:
data = {
"result":
{
"corrList":[
{
"corrId":123456,
"title":"sample1",
},
{
"corrId":45678,
"title":"sample2",
},
{
"corrId":987654,
"title":"sample3",
}
],
"find":True
}
}
corrList = [item for item in data['result']['corrList'] if 'corrId' in item]
print(len(corrList))
輸出 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.