简体   繁体   English

如何使用python计算json响应中的值出现次数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM