Home > Software design >  Python - Check if json array has multiple objects
Python - Check if json array has multiple objects

Time:08-12

I am trying to parse data from an output from a router, however sometimes two duplicate values. Because of this, I need to check for 3 possibilities, one MAC, two MACs and no MAC.

This is what I currently have:

            else: #Starts the parse
                parser5 = ttp(output5, template_05_ad)
                parser5.parse()
                #put result in JSON format
                results_0 = parser5.result(format='json')[0]
                #str to list **convert with json.loads
                result_0 = json.loads(results_0)

                #Places the results into variables
                if 'mac' in result_0[0][0]:
                    mac_connected = str(result_0[0][0]['mac'])
                elif 'mac' in result_0[0]:
                    mac_connected = str(result_0[0]['mac'])
                else:
                    mac_connected = 'NULL'

With outputs looking like the following:

One MAC:
                                                             CE 
Vlan     Mac Address       Type        Interface      CTag  Vlan
----  -----------------  ---------  ----------------  ----  ----
4065  E1:B4:19:64:1B:51  Dynamic    10/0/1@1/2/2      na    na  
Total MAC addresses for this criterion: 1

Two MAC:
                                                             CE 
Vlan     Mac Address       Type        Interface      CTag  Vlan
----  -----------------  ---------  ----------------  ----  ----
4065  E1:B4:19:64:1B:51  Dynamic    10/0/1@1/2/2      na    an  
4065  E1:B4:19:64:1B:51  Dynamic    10/0/1@1/2/2      na    na  
Total MAC addresses for this criterion: 1

No MAC:
No MAC addresses found for this criterion

When it gets parsed it will look like this (printed output from result_0):

One MAC::
[{'mac': 'E1:B4:19:64:1B:51'}]

Two MAC:
[[{'mac': 'E1:B4:19:64:1B:51'}, {'mac': 'E1:B4:19:64:1B:51'}]]

No MAC:
[{}]

Sorry if this has been answered before, any help would be appreciated, thanks.

CodePudding user response:

I'm not sure about how you would like the data returned, but this could maybe help you getting closer to a solution?

def CheckMAC(mac):
    connected_mac = ""
    for value in mac:
        if value:
            if isinstance(value, dict):
                return(value['mac'])
            elif isinstance(value, list):
                for nested_value in value:
                    connected_mac  = f"{nested_value['mac']} "
                return(connected_mac.strip())
        else:
            return("NULL")

oneMAC = [{'mac': 'E1:B4:19:64:1B:51'}]
twoMAC = [[{'mac': 'E1:B4:19:64:1B:51'}, {'mac': 'E1:B4:19:64:1B:51'}]]
noMAC = [{}]

print(CheckMAC(oneMAC))
print(CheckMAC(twoMAC))
print(CheckMAC(noMAC))

Results:

E1:B4:19:64:1B:51
E1:B4:19:64:1B:51 E1:B4:19:64:1B:51
NULL

CodePudding user response:

If I understand correctly, you either get a list of dictionaries or a single json dictionary as value for result_0[0].

You can simply check whether it is a list first. Since you are always only interested in the first mac value, you can just work with the first list element in that case. If you then use the .get() method with a default value, you do not need to treat the empty case as separate:

            else: #Starts the parse
                parser5 = ttp(output5, template_05_ad)
                parser5.parse()
                #put result in JSON format
                results_0 = parser5.result(format='json')[0]
                #str to list **convert with json.loads
                result_0 = json.loads(results_0)

                if isinstance(result_0[0], list):
                    result_0[0] = result_0[0][0]

                #Places the results into variables
                mac_connected = result_0[0].get('mac', 'NULL')

(this assumes that in the list case, the mac result you want in the end is always in result[0][0])

Another option might be to adjust your TTP template in a way so it always returns a list (even if there is only one element in it) in the first place.

  • Related