Python json print specific keys

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.

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

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)

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)

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

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

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

Python json print specific keys

Python json print specific keys

In this Python tutorial we are going to see how we can get all the keys in this json object and also all the values of the keys.

okay so let me get started let me take one empty python file
here, so yeah so let me save this file first as example.py.

Load json

As it is a json i need to import this package called json. This lets you play around with json. Then it is available in this particular Python file.

import json

Enter fullscreen mode Exit fullscreen mode

Right so take that file path and try to open that with open as json file.

with open("C:\\pythonPrograms\\example.json") as jsonFile:

Enter fullscreen mode Exit fullscreen mode

That will do json decoding. Our json file looks like this:

    {"emp_details":[
             {"name": "a",
              "id": "123"
             },
             {"name":"b",
              "id":"345"
             }
    ]
    }

Enter fullscreen mode Exit fullscreen mode

You need to give the file name, so this is my file name. It should have double slashes not the single slash, so once we have this using the json library that we have imported you need to load the json object. Let's go.

Python json print specific keys

Get keys and values

Using load function json file, this let me keep it into a variable called data.

    data = json.load(jsonFile)

Enter fullscreen mode Exit fullscreen mode

Then you have a Python object. Now you can get the keys and values. The code below depends on what your json file looks like. In our json file there's a header named emp_details.

    jsonData = data["emp_details"]
    keys = x.keys()
    values = x.values()

Enter fullscreen mode Exit fullscreen mode

That gives us this code:

    import json

    with open("test.json") as jsonFile:
        data = json.load(jsonFile)
        jsonData = data["emp_details"]
        for x in jsonData:
            keys = x.keys()
            print(keys)
            values = x.values()
            print(values)

Enter fullscreen mode Exit fullscreen mode

It will output:

{'name': 'a', 'id': '123'}
dict_keys(['name', 'id'])
dict_values(['a', '123'])
{'name': 'b', 'id': '345'} 
dict_keys(['name', 'id'])
dict_values(['b', '345'])

Enter fullscreen mode Exit fullscreen mode

If you want, you can loop over the keys and values inside the loop, to do the formatting.

Here we use a for loop to iterate over the keys and values. If your json file is small like the one in this example, you don't necessarily have to use a loop.

That's all :-)

How do I read a JSON key in Python?

Get all keys and values from json object in Python.
{"emp_details":[ {"name": "a", "id": "123" }, {"name":"b", "id":"345" } ] }.
data = json. load(jsonFile).
jsonData = data["emp_details"] keys = x. keys() values = x. ... .
import json with open("test.json") as jsonFile: data = json..

How do I find my JSON key?

To get key and value from json object in javascript, you can use Object. keys() , Object. values() , for Object. entries() method the methods helps you to get both key and value from json object.

How do you iterate through a JSON string in Python?

Use json..
Copy import json jsonstring1 = '{"k1": "v1", "k2": "v2"}' #Load JSON string into a dictionary json_dicti = json. ... .
Copy {"fullname": "Tom", "languages": ["English", "German"] }.

How do I read a nested JSON file in Python?

Use pd. read_json() to load simple JSONs and pd. json_normalize() to load nested JSONs. You can easily access values in your JSON file by chaining together the key names and/or indices.