![]() |
Code failed JSON KeyError - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Code failed JSON KeyError (/thread-32021.html) |
Code failed JSON KeyError - popps - Jan-15-2021 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 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 RE: Code failed JSON KeyError - buran - Jan-15-2021 desc = items.get("desc") # the default value is None desc = items.get("desc", '') # the default value is empty str '' RE: Code failed JSON KeyError - popps - Jan-15-2021 I have insert this code, but the error as the same RE: Code failed JSON KeyError - buran - Jan-15-2021 (Jan-15-2021, 03:36 PM)popps Wrote: I have insert this code, but the error as the sameBecause 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 |