如何通过python

时间:2019-01-11 00:22:05

标签: python json api

我能够获得api请求的响应,并让它提供我所有的详细信息。我解码json response.json()并使用open()和json.dump创建文件。我可以在列表中看到该对象的所有键和值。接下来,我想获取一个特定的键/值,以便可以将其用作其他python脚本的输入。

我能够从api请求并解码json,并通过json.dump创建json文件并列出所有对象。

我用于查询和创建json文件的python代码。

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)

这是我使用netmiko模块访问设备的代码

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)

要通过ssh访问数组'device ['ip']中的设备,这些设备将返回包含所有详细信息(例如登录名/ ip /密码)的json文件。

api查询的

JSON响应,下面是所有详细信息; 从这个......

{
   "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"
         }
    ]
}

我只想提取用户名,IP和密码的键和值,并且仍采用下面的json格式。 对此。。。

{
      "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"
            }
      ]
 }

我无法从每个对象中提取特定的键和值,并且无法以json列表格式进行打印。

如果我的其他帖子,则此问题属于一个问题,但我将其设为单独的问题,因为该帖子已得到回答,并避免造成任何混淆。我真的需要专家的帮助,我们将非常感谢您的支持和指导。谢谢

3 个答案:

答案 0 :(得分:0)

尝试以下工作代码:

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'])

答案 1 :(得分:0)

您可以像这样使用列表理解和字典:

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)

在您的代码中:

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)

答案 2 :(得分:-1)

print(json.dumps(json_object['defaultName'], sort_keys=True, indent=4))