For reference, let's see what the original JSON would look like, with pretty formatting:

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}

That lets us see the structure of the data more clearly.

In the specific case, first we want to look at the corresponding value under the 'value' key in our parsed data. That is another dict; we can access the value of its 'queryInfo' key in the same way, and similarly the 'creationTime' from there.

To get the desired value, we simply put those accesses one after another:

my_json['value']['queryInfo']['creationTime'] # 1349724919000
Answer from dm03514 on Stack Overflow
Top answer
1 of 5
91

For reference, let's see what the original JSON would look like, with pretty formatting:

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}

That lets us see the structure of the data more clearly.

In the specific case, first we want to look at the corresponding value under the 'value' key in our parsed data. That is another dict; we can access the value of its 'queryInfo' key in the same way, and similarly the 'creationTime' from there.

To get the desired value, we simply put those accesses one after another:

my_json['value']['queryInfo']['creationTime'] # 1349724919000
2 of 5
23

I just need to know how to translate that into specific code to extract the specific value, in a hard-coded way.

If you access the API again, the new data might not match the code's expectation. You may find it useful to add some error handling. For example, use .get() to access dictionaries in the data, rather than indexing:

name = my_json.get('name') # will return None if 'name' doesn't exist

Another way is to test for a key explicitly:

if 'name' in resp_dict:
    name = resp_dict['name']
else:
    pass

However, these approaches may fail if further accesses are required. A placeholder result of None isn't a dictionary or a list, so attempts to access it that way will fail again (with TypeError). Since "Simple is better than complex" and "it's easier to ask for forgiveness than permission", the straightforward solution is to use exception handling:

try:
    creation_time = my_json['value']['queryInfo']['creationTime']
except (TypeError, KeyError):
    print("could not read the creation time!")
    # or substitute a placeholder, or raise a new exception, etc.
🌐
ReqBin
reqbin.com › code › python › rituxo3j › python-requests-json-example
How do I get JSON using the Python Requests?
To request JSON data from the server using the Python Requests library, call the request.get() method and pass the target URL as a first parameter. The Python Requests Library has a built-in JSON decoder and automatically converts JSON strings ...
🌐
PYnative
pynative.com › home › python › json › parse a json response using python requests library
Parse a JSON response using Python requests library
May 14, 2021 - The requests module provides a builtin JSON decoder, we can use it when we are dealing with JSON data. Just execute response.json(), and that’s it. response.json() returns a JSON response in Python dictionary format so we can access JSON using key-value pairs. You can get a 204 error In case the JSON decoding fails.
🌐
GeeksforGeeks
geeksforgeeks.org › response-json-python-requests
response.json() - Python requests - GeeksforGeeks
4 weeks ago - Whenever we make a request to a specified URI through Python, it returns a ... In Python’s requests library, the response.text attribute allows developers to access the content of the response returned by an HTTP request. This content is always returned as a Unicode string, making it easy to read and manipulate. Whether the response body contains HTML, JSON, XML, or plain text
🌐
TutorialsPoint
tutorialspoint.com › python-program-to-extract-a-single-value-from-json-response
Python program to extract a single value from JSON response
July 12, 2023 - The JSON objects are converted into dictionaries with the help of "json()" method. These dictionaries are then parsed to pick specific information. Here, we will extract the BPI value by accessing the nested objects. The dictionary keys refer to certain attributes and properties and their values ...
🌐
Python.org
discuss.python.org › python help
REST API Call ---Extract Value from Specific Key from Response - Python Help - Discussions on Python.org
January 22, 2024 - response = requests.request("GET", url, headers=headers, data=payload, verify=False) My response variable contains a response from an HTTP request and I need to extract the ID value under the Items array. {'links': {'s…
🌐
CodeSpeedy
codespeedy.com › home › python program to extract a single value from json response (using api call)
Python program to extract a single value from JSON response(Using API call)
March 20, 2024 - To perform this task we will be going to use the request module in Python, this module allows users to send HTTP requests and receive responses in form of JSON. ... import urllib.parse import requests base_url="https://v6.exchangerate-api.com/v6/Enter your API key here/pair/" print("Enter the First Currency") s=input() print("Enter the Second Currency") l=input() value=s+"/"+l url = base_url+value json_data = requests.get(final_url).json() result = json_data['conversion_rate'] print("Conversion rate from "+s+" to "+l+" = ",result)
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 65328611 › how-to-select-and-print-a-specific-json-value-using-python-get-request
How to select and print a specific JSON value using Python GET Request - Stack Overflow
February 12, 2025 - Can you be more specific? Which "identifier" are you trying to access? Let's assume you want to access the dayOfWeek tag for each workout, then you can do something like this: workouts_list = getBooking.json()["map"]["response"][0]["workouts"] for workout in workouts_list: print(workout["dayOfWeek"]) You can do the same thing for other parameters as well by just replacing dayOfWeek to any of the tags available on the JSON response. ... Sorry, I am trying to get a "identifier" for a specific day.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-extract-a-single-value-from-json-response
Python program to extract a single value from JSON response - GeeksforGeeks
August 20, 2025 - Python · # importing required module import urllib.parse import requests # setting the base URL value baseUrl = "https://v6.exchangerate-api.com/v6/0f215802f0c83392e64ee40d/pair/" First = input("Enter First Currency Value") Second = input("Enter Second Currency Value") result = First+"/"+Second final_url = baseUrl+result # retrieving data from JSON Data json_data = requests.get(final_url).json() Final_result = json_data['conversion_rate'] print("Conversion rate from "+First+" to "+Second+" = ", Final_result) Output: USD To INR ·
🌐
Bright Data
brightdata.com › faqs › json › extract-json-response-python
How to Extract Data from a JSON Response in Python?
April 17, 2025 - With the JSON data parsed into a Python dictionary, you can extract specific values. For instance, if the JSON response looks like this: { "user": { "id": 123, "name": "John Doe", "email": "[email protected]" } } Here’s the complete code in ...
🌐
w3resource
w3resource.com › python-exercises › requests › python-request-exercise-5.php
Python: Send a request to a web page, and print the JSON value of the response - w3resource
September 18, 2023 - Write a Python program to send a request to a web page, and print the JSON value of the response. Print each key value in the response. ... import requests r = requests.get('https://api.github.com/') response = r.json() print("JSON value of the said response:") print(r.json()) print("\nEach key of the response:") print("Current user url:",response['current_user_url']) print("Current user authorizations html url:",response['current_user_authorizations_html_url']) print("Authorizations url:",response['authorizations_url']) print("code_search_url:",response['code_search_url']) print("commit_searc
Top answer
1 of 3
4

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)
2 of 3
-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'])
🌐
Towards Data Science
towardsdatascience.com › home › latest › json and apis with python
JSON and APIs with Python | Towards Data Science
October 22, 2013 - In fact, in order for us to parse through this and extract what we want from it, we will eventually turn it into a python dictionary object. Upon inspection, we can see that it looks like a nested dictionary. The outer dictionary has the keys ‘Global’ (with a value of a dictionary) and ‘Countries’ (with a value of a list that is made up of dictionaries, with each dictionary corresponding to a specific country). ... So let’s open a jupyter notebook and request the information from that [U](https://api.covid19api.com/summary)RL.
🌐
datagy
datagy.io › home › python requests › response.json() – working with json in python requests
response.json() - Working with JSON in Python requests • datagy
February 4, 2026 - The requests library comes with a helpful method, .json(), that helps serialize the response of the request. In order to look at an example, let’s the public endpoints provided by the website reqres.in. These endpoints work without signing up, so following along with the tutorial is easy. Let’s see how we can access the /users endpoint and serialize the response into a Python dictionary using the .json() method: # Serializing a GET Request with .json() import requests resp = requests.get('https://reqres.in/api/users') resp_dict = resp.json() print(type(resp_dict)) # Returns: <class 'dict'>
🌐
Medium
medium.com › @themathlab › api-requests-json-parsing-in-python-a-guide-in-data-collection-31e985981ea3
API Requests & JSON Parsing in Python: A Guide in Data Collection | by The Math Lab | Medium
April 2, 2025 - We can see the status code is 200 which means the request was successful. By using response.text we have printed the raw JSON response. ... The raw JSON response isn't well structured so it is hard to manipulate and access data in this format. Therefore it is clear that we need to convert JSON string into a usable data structure for easier manipulation and access within the program. This process is called JSON parsing. In Python, we can convert JSON string into a Python dictionary.
🌐
Python Pool
pythonpool.com › home › blog › python requests json: a comprehensive guide
Python Requests JSON: A Comprehensive Guide - Python Pool
March 16, 2021 - Assuming you have received a JSON object as a response from a server using the Requests library, you can use the in keyword to check if a specific key exists in the JSON object: import requests response = requests.get('https://example.com/api/data') ...