简体   繁体   English

如何通过python在json中选择对象的特定键/值

[英]How to select specific key/value of an object in json via python

I'm able to get response of api request and have it give me all the details.我能够得到 api 请求的响应,并让它给我所有的细节。 I decode the json response.json() and create the file with open() and json.dump.我解码 json response.json() 并使用 open() 和 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.接下来我想获得一个特定的键/值,以便我可以将它用作我其他 python 脚本的输入。

I am able to request from api and decode the json and create json file via json.dump and list all of the objects.我能够从 api 请求并解码 json 并通过 json.dump 创建 json 文件并列出所有对象。

My python code to query and create the json file.我的python代码来查询和创建json文件。

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这是我使用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)

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.将 ssh 访问到数组 'device['ip'] 中的设备,这些设备指回包含所有详细信息(例如登录名/ip/密码)的 json 文件。

JSON response from api query that response all the details are below;来自 api 查询的 JSON 响应,该响应的所有详细信息如下; 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.我只想提取用户名、ip 和密码的键和值,并且仍然是下面的 json 格式。 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.我无法从每个对象中提取特定的键和值,并如上所述以 json 列表格式打印。

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谢谢

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)

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'])
print(json.dumps(json_object['defaultName'], sort_keys=True, indent=4)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM