How to Extract a Single Value from a JSON Response

How can I extract a single value from a JSON response?

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

How to get a single value from a json response using PowerShell

Once you have converted your JSON into an object, you can use Where-Object or Where to filter the list array element that contains id with a non-empty and non-null value. Then use the member access operator . to retrieve the value of the id property.

$json = @"
{
"page": {
"offset": 0,
"total": 36,
"totalFilter": 1
},
"list": [
{
"id": "41",
"type": "ATBR",
"hostName": "AAMS",
"userId": "",
"userName": "",
"status": "CONNECTED",
"poolName": "",
"fullyQualifiedHostName": "-",
"updatedBy": "mscr",
"updatedOn": "2020-06-24T23:28:11.239894Z",
"botAgentVersion": "9.0"
}
]
}
"@

$x = $json | ConvertFrom-Json
$id = ($x.list | Where id).id

Using Where id basically checks if [boo]$x.list.id returns true. So if you were to use Where userId, it would return nothing since [bool]$x.list.userId evaluates to false.


You can alternatively retrieve the id value using Select-Object:

$id = $x.list | Where id | Select-Object -Expand id

Note that if you have more than one object in list (since it is an array) that contains id with a value, multiple id values will be returned.

How to extract a single value from JSON response (with Python)?

Pretty-printing your data makes it a lot easier to analyze. Once you do that, as in my edit above, you'll see that you can access "mood" via data["photos"][0]["tags"][0]["attributes"]["mood"], assuming your dict is named data.

You need the numeric list indices because both "photos" and "tags" are lists containing a single element - a dict.

How to extract specific values from JSON

In this example, variable req_camera_id contains the camera_id that you want to match. So you loop over the sub-dictionaries as necessary. But I don't think you need a recursive call in this case.

import requests

req_camera_id = '1501'

endpoint = 'https://api.data.gov.sg/v1/transport/traffic-images'
response = requests.get(endpoint)
if response.status_code == 200:
data = response.json()
for item in data['items']:
for cam in item['cameras']:
camera_id = cam['camera_id']
if camera_id == req_camera_id:
image = cam['image']
print(f'{camera_id} {image}')

gives:

1501 https://images.data.gov.sg/api/traffic-images/2020/07/4c62761d-450d-4aa1-895f-c16482fa620f.jpg

How do I extract value from Json

see this code what i am used in my application

String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";

I retrieved like this

JSONObject json = (JSONObject) JSONSerializer.toJSON(data);        
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");

System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );

How do I extract specific values from the JSON response in Postman using a test?

Let's walk through it:

var response = JSON.parse(responseBody);

JSON.parse() is taking the JSON response in as a string, and converting it to a JS object, which will then be stored in response.

response.map(...)

The map() function is called on an array and takes a function as a parameter. It calls the function you provide it once for each element in the array that it's called on.

For your particular case, we'll need to modify this a little, since response is an object, rather than an array, and the value you're after, name, is nested in the entries array inside of response. To account for this, we're going to call map() directly on the nested array, and set it equal to a new variable to store the result, like this:

var names = response.entries.map(...);

Now, we can pass map() a function that will extract the name from each element in the entries array. Our function needs to accept the array element as a parameter, and return the extracted name so that map() can add it to the new array it's making.

function(entry) {
return entry.accessible_by.name;
}

In the end, we end up with this:

var response = JSON.parse(responseBody);

var names = response.entries.map(function(entry) {
return entry.accessible_by.name;
});

console.log(names);

This will output an array of names to your browser console. ["Test", ...]

Bonus:
With a little JavaScript syntactic sugar (specifically arrow functions), we can make the function code a little cleaner:

var response = JSON.parse(responseBody);

var names = reponse.entries.map(entry => entry.accessible_by.name);

console.log(names);


Related Topics



Leave a reply



Submit