close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to select specific key/value of an object in json via python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to select specific key/value of an object in json via python?

  1. How to select specific key/value of an object in json via python?

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

  2. select specific key/value of an object in json via python

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

Method 1

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)

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read