【问题标题】:How to count value occurrences in json response using python?如何使用python计算json响应中的值出现?
【发布时间】:2021-06-22 13:04:01
【问题描述】:

我有一个如下所示的 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()

有人可以帮忙吗?提前致谢!

【问题讨论】:

  • 使用len(data['result']['corrList'])

标签: python arrays json


【解决方案1】:

您需要实际计算拥有该密钥的dicts 的数量:

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

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 2019-03-02
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2015-01-08
    • 2017-05-20
    相关资源
    最近更新 更多