简体   繁体   中英

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.

{
  "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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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