有条件地计算嵌套python json dict中的值数

有条件地计算嵌套python json dict中的值数,python,json,dictionary,Python,Json,Dictionary,我有一个json响应对象 我想计算state=health d= { "ResponseMetadata": { "HTTPHeaders": { "content-length": "444", "content-type": "text/xml", "date": "Tue, 12 Nov 2019 02:30:11 GMT", "x-amzn-requestid":

我有一个json响应对象 我想计算state=
health

d= {
    "ResponseMetadata": {
        "HTTPHeaders": {
            "content-length": "444", 
            "content-type": "text/xml", 
            "date": "Tue, 12 Nov 2019 02:30:11 GMT", 
            "x-amzn-requestid": "1234"
        }, 
        "HTTPStatusCode": 200, 
        "RequestId": "1234", 
        "RetryAttempts": 0
    }, 
    "TargetHealthDescriptions": [
        {
            "HealthCheckPort": "80", 
            "Target": {
                "Id": "i-dummy", 
                "Port": 80
            }, 
            "TargetHealth": {
                "State": "healthy"
            }
        }, 
        {
            "HealthCheckPort": "80", 
            "Target": {
                "Id": "i-testing", 
                "Port": 80
            }, 
            "TargetHealth": {
                "State": "healthy"
            }
        }
    ]
}
我试过:

count = 0
for x,y in d.items():
    if y['State'] == 'healthy':
        count += 1
print(count)
但它抱怨道

Traceback (most recent call last):
  File "deploy_staging_web.py", line , in <module>
    if y['State'] == 'healthy':
TypeError: list indices must be integers, not str
回溯(最近一次呼叫最后一次):
文件“deploy_staging_web.py”,第行,在
如果y['State']=='health':
TypeError:列表索引必须是整数,而不是str
如何绕过它?

您可以使用递归:

def get_sum(d):
  val = 0 if not isinstance(d, dict) else d.get('State') == 'healthy'
  return val+sum(get_sum(i) for i in getattr(d, 'values', lambda :d)() if isinstance(i, (dict, list)))

print(get_sum(d))
输出:

2