1

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

chenoi
  • 575
  • 3
  • 8
  • 30

3 Answers3

4

You can use list comprehension and dict like this:

device_disco["device"] =[dict(username=k1["username"],password=k1["password"],ip=k1["ip"]) for k1 in 
device_disco["device"]]

jsonData = json.dumps(device_disco)
print (jsonData)

in your code:

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)
device_disco["device"] =[dict(username=k1["username"],password=k1["password"],ip=k1["ip"]) for k1 in 
device_disco["device"]]

jsonData = json.dumps(device_disco)


with open('devices.json', 'w') as fp:
json.dump(jsonData, fp, indent=4, sort_keys=True)
Mehrdad Dowlatabadi
  • 1,335
  • 2
  • 9
  • 11
  • Hi thanks sir. The details of name/ip/etc is getting via private api (i have no control of this api and I can make my request based on api provided) and the content might be change and updated. I can get all the details and from there I hope I can modified which key/value that i require (this part is my problem). Also the key/value that i require shall maintain in the json format {"device":[{},{},{}]}. – chenoi Jan 11 '19 at 01:03
  • @chenoi check my edited answer , you just need to convert jason data to dict and then do the process – Mehrdad Dowlatabadi Jan 11 '19 at 01:28
  • Hi sir the json convert json.loads() will not list the keys/values (username,ip,password) that i want....it will load everything.. – chenoi Jan 11 '19 at 01:46
  • After loading whole json data to variable you can use my code – Mehrdad Dowlatabadi Jan 11 '19 at 01:47
  • the data call from api can be change from time to time, thus i need to request it every time i want to access the devices to ensure im getting the latest update ip/username/password... i cannot every time have to hardcoded the json string in my code... – chenoi Jan 11 '19 at 01:52
  • is your json data in device_disco? – Mehrdad Dowlatabadi Jan 11 '19 at 01:54
  • Looks good...i will simulate and run it to be verified further. Thanks – chenoi Jan 11 '19 at 02:57
  • Yes sir. it works. Thanks for your attention and good support. – chenoi Jan 11 '19 at 10:52
  • @chenoi glad i could help. – Mehrdad Dowlatabadi Jan 11 '19 at 12:22
-2

Try this working code:

import json
import sys

data={
   "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"
         }
    ]
}
json_str = json.dumps(data)
resp = json.loads(json_str)
print (resp['device'][0]['username'])
Abhishek
  • 5
  • 6
  • Hi thanks sir. I just need few keys/values from all the keys listed. – chenoi Jan 11 '19 at 01:41
  • Here is the working code for you: import json import sys data={put you JSON here} json_str = json.dumps(data) resp = json.loads(json_str) print (resp['device'][0]['username']) – Abhishek Jan 12 '19 at 14:40
-2
print(json.dumps(json_object['defaultName'], sort_keys=True, indent=4)) 
Zoe
  • 27,060
  • 21
  • 118
  • 148