Home > Blockchain >  Python - JSON count number of element [closed]
Python - JSON count number of element [closed]

Time:10-02

I'm facing an issue while counting elements in an JSON response.

This is the response I get from the API:

{
'mgmtResponse': 
{
    '@responseType': 'operation', 
    '@requestUrl': 'https://10.67.210.219/webacs/api/v1/op/enablement/inventory/stacks?deviceIpAddress=10.135.31.136', 
    '@rootUrl': 'https://10.67.210.219/webacs/api/v1/op', 
    'clusterInventoryStackDTO': 
    [
        {
            'entPhysicalIndex': 2001, 
            'macAddress': '7c:21:0d:11:7d:00', 
            'role': 'MEMBER', 'softwareImage': 'C2960X-UNIVERSALK9-M', 
            'stackSwitchId': 2, 
            'state': 'READY', 
            'switchPriority': 14
        }, 
        {
            'entPhysicalIndex': 3001, 
            'macAddress': '7c:21:0d:10:50:80', 
            'role': 'MEMBER', 
            'softwareImage': 'C2960X-UNIVERSALK9-M', 
            'stackSwitchId': 3, 
            'state': 'READY', 
            'switchPriority': 13
        },
        {
            'entPhysicalIndex': 5001, 
            'macAddress': '54:8a:ba:98:de:80', 
            'role': 'MEMBER', 'softwareImage': 
            'C2960X-UNIVERSALK9-M', 
            'stackSwitchId': 5, 
            'state': 'READY', 
            'switchPriority': 11
        }, 
        {
            'entPhysicalIndex': 1001, 
            'macAddress': '7c:21:0d:07:4a:80', 
            'role': 'MASTER', 
            'softwareImage': 'C2960X-UNIVERSALK9-M', 
            'stackSwitchId': 1, 
            'state': 'READY', 
            'switchPriority': 15
        }, 
        {
            'entPhysicalIndex': 4001, 
            'macAddress': '00:9a:d2:23:28:80', 
            'role': 'MEMBER', 
            'softwareImage': 'C2960X-UNIVERSALK9-M', 
            'stackSwitchId': 4, 
            'state': 'READY', 
            'switchPriority': 12
        }
    ]
}

}

I'm trying to count elements in "ClusterInventoryStackDTO" (5 elements in the example). But I'm unable to get the right number.

If I try:

len(stackResult["mgmtResponse"])

It returns me the number 4. Probably it counts "@responseType", "@requestURL", "@rootUrl" and "clusterInventoryStackDTO".

If I try:

len(stackResult["mgmtResponse"]["clusterInventoryStackDTO"])

I get a "key error". If I test the JSON path I get the right objects, just counting them is failing.

Can you please help me with this ?

Regards,

hjacquemin

CodePudding user response:

Try to use this:

len(stackResult["mgmtResponse"].get("clusterInventoryStackDTO", []))
  • Related