[英]How to count value occurrences in json response using python?
I have a json response that looks like below and I would like to count how many times corrId
has been mentioned.我有一个如下所示的 json 响应,我想计算
corrId
被提及的次数。
{
"result":
{
"corrList":[
{
"corrId":123456,
"title":"sample1",
},
{
"corrId":45678,
"title":"sample2",
},
{
"corrId":987654,
"title":"sample3",
}
],
"find":true
}
}
For the above, I would expect result to be 3
对于上述,我希望结果是
3
I have tried something like above, but it throws an error:我已经尝试过类似上面的方法,但它会引发错误:
r = requests.get(url = HOSTNAME + endpoint, headers = headers, verify=False)
data = json.loads(r.text)
corrList = len(data['corrList'][0]['corrId'])
print (corrList)
My error:我的错误:
TypeError: object of type 'int' has no len()
Would someone be able to help?有人可以帮忙吗? thanks in advance!
提前致谢!
You need to actually count the number of dict
s that have that key:您需要实际计算具有该键的
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))
Output 3输出 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.