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

查看:22
本文介绍了如何通过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.

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

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.

来自 api 查询的 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天全站免登陆