如何通过python在json中选择对象的特定键/值 [英] How to select specific key/value of an object in json via python

查看:206
本文介绍了如何通过python在json中选择对象的特定键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I am able to request from api and decode the json and create json file via json.dump and list all of the objects.

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

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)

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

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)

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

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响应,其所有详细信息均在下面; 从这个......

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

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

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

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

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

推荐答案

您可以像这样使用列表推导和字典:

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)

在您的代码中:

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)

这篇关于如何通过python在json中选择对象的特定键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆