I'm able to get response of api request and have it give me all the details. I decode the json response.json() and create the file with open() and json.dump. I am able to see all the keys and values of the object in the list. Next I would like to get a specific key/value so I can use it as an input to my other python script.
I am able to request from api and decode the json and create json file via json.dump and list all of the objects.
My python code to query and create the json file.
import requests
import json
#API request details
url = 'api url'
data = '{"service":"ssh", "user_id":"0", "action":"read_by_user",
"user":"D2", "keyword":"NULL"}'
headers = {"Content-Type": "application/json"}
#Making http request
response = requests.post(url,data=data,headers=headers,verify=False)
print(response)
#Json string
json_disco = response.text
print(type(json_disco))
print(json_disco)
#Decode response.json() method to a python dictionary and use the data
device_disco = response.json()
print(type(device_disco))
print(device_disco)
with open('devices.json', 'w') as fp:
json.dump(device_disco, fp, indent=4, sort_keys=True)
This is the code that i use netmiko module to access equipment
with open('devices.json') as dev_file:
devices = json.load(dev_file)
print(devices)
netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
netmiko.ssh_exception.NetMikoAuthenticationException)
for device in devices['device']:
try:
print('~' * 79)
print('Connecting to device:',device['ip'])
connection = netmiko.ConnectHandler(**device)
print(connection.send_command('show interfaces'))
connection.disconnect()
except netmiko_exceptions as e:
print('Failed to ', device['ip'], e)
To access ssh to the devices in array 'device['ip'] which refer back to the json file that contain all the details such as login name/ip/password.
JSON response from api query that response all the details are below; FROM THIS....
{
"status": "SUCCESS",
"device": [
{
"model":"XXXX-A",
"username": "login1",
"ip": "10.10.10.1",
"password": "123",
"device_type": "cisco_ios"
},
{
"model":"XXXX-A",
"username": "login2",
"ip": "10.10.10.2",
"password": "456",
"device_type": "cisco_ios"
},
{
"model":"XXXX-A",
"username": "login3",
"ip": "10.10.10.3",
"password": "test",
"device_type": "cisco_ios"
}
]
}
I want to extract only the key and value of username, ip and password and still in the json format below. TO THIS....
{
"status": "SUCCESS",
"device": [
{
"username": "login1",
"ip": "10.10.10.1",
"password": "123"
},
{
"username": "login2",
"ip": "10.10.10.2",
"password": "456"
},
{
"username": "login3",
"ip": "10.10.10.3",
"password": "test"
}
]
}
I am not able to extract specific keys and values from each object and print in json list format as above.
This question is part of one if my other posts but I made it a separate question as that post was already answered and to avoid any confusion. I really need expert help, support and guidance would be much appreciated. Thanks