Python Forum

Full Version: Code failed JSON KeyError
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am trying to retrieve information on network equipment, but I have the following error and I do not know how to handle it


Error:
connect : xxxxx {"device": "switch_1", "interface": "Ethernet1/1", "description": "xxxxxx"} {"device": "switch_1", "interface": "Ethernet1/2", "description": "xxxxxx"} {"device": "switch_1", "interface": "Ethernet1/3", "description": "xxxxxx"} Traceback (most recent call last): File "test_mac_inv.py", line 51, in <module> desc = items["desc"] KeyError: 'desc'
I know where this error came from. At times I don't have the description information.
How can I make the code go to the next JSON line and not do the KeyError?

Thank's
My code
 IP =  ["xxx.xxx.xxx.xxx"]
 #SSH INIT
 ssh = paramiko.SSHClient()
 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

 username = "xxxxxx"
 password = "xxxxxxx"
 port = 22

 for swi in IP:
         Connection = "connect : " + swi
         print Connection
 #GET hostname
         ssh.connect(swi, port, username, password, look_for_keys=False)
         stdin,stdout,stderr = ssh.exec_command('show hostname ')
         host = str(stdout.readlines()[0].strip())
 #GET desc
         ssh.connect(swi, port, username, password, look_for_keys=False)
         stdin,stdout,stderr = ssh.exec_command('show interface description | json ')
         output = stdout.readlines()

         #GET OUTPUT
         JSON_DATA = json.loads('\n'.join(output))

         for items in JSON_DATA["TABLE_interface"]["ROW_interface"]:
              interface = items["interface"]
              desc = items["desc"]
              Cisco_Inventory = { "device" : host, "interface" : str(items["interface"]), "description" : str(items["desc"])}
              print Cisco_Inventory
desc = items.get("desc") # the default value is None
desc = items.get("desc", '') # the default value is empty str ''
I have insert this code, but the error as the same
(Jan-15-2021, 03:36 PM)popps Wrote: [ -> ]I have insert this code, but the error as the same
Because you don't use desc name defined on line 27, but on line 28 again retrieve the value from the dict. Same for interface (defined on line 26)

And please, always post the full traceback in error tags