Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code failed JSON KeyError
#1
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
Reply


Messages In This Thread
Code failed JSON KeyError - by popps - Jan-15-2021, 02:47 PM
RE: Code failed JSON KeyError - by buran - Jan-15-2021, 03:24 PM
RE: Code failed JSON KeyError - by popps - Jan-15-2021, 03:36 PM
RE: Code failed JSON KeyError - by buran - Jan-15-2021, 03:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Request for Python code - Features extraction from JSON file (cuckoo) thinker 1 2,219 Apr-07-2021, 04:40 PM
Last Post: Larz60+
  API JSON response missing list gives keyerror rolfmadsen 3 3,515 Mar-28-2020, 10:12 AM
Last Post: buran
  json.dumps save some unicode chars as code, not char buran 1 2,938 Aug-02-2018, 04:02 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020