Parsing values from multi-level JSON Array
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-23-2020 01:45 PM
Hi,
I am retrieving data from Google Admin. The goal is to retrieve the most recent device users from the customer and update their hardware assets in our instance with the most recent user periodically.
The response body I get looks like this:
{
"chromeosdevices": [
{
"serialNumber": "F88B473",
"lastSync": "2020-10-25T07:01:21.772Z",
"recentUsers": [
{
"type": "USER_TYPE_MANAGED",
"email": "madeup_name@mail.com"
}
]
},
{
"serialNumber": "5CD13786X9",
"lastSync": "2020-10-14T07:29:47.104Z"
},
{
"serialNumber": "NXHKLED00J08132D917600",
"lastSync": "2020-11-03T10:09:58.319Z",
"recentUsers": [
{
"type": "USER_TYPE_MANAGED",
"email": "madeup_name2@mail.com"
},
{
"type": "USER_TYPE_MANAGED",
"email": "madeup_name3@mail.com"
}
]
}
]
}
This response body has been shortened for brevity. I retrieve all their devices at once. What I need to do is iterate through the chromedevices array and each individual recentUsers array (the first user in every recentUsers is the most recent one), so I can put serialNumber and email together and update our records.
I've gotten so far as getting my hands on the serial numbers using a regular for loop:
var obj = JSON.parse(responseBody);
for (i = 0; i < obj.chromeosdevices.length; i++) {
gs.print(obj.chromeosdevices[i].serialNumber);
}
But I am stumped as to how I can get my hands on the emails and put them together.
Anyone got any pointers? 🙂
- Labels:
-
Integrations
-
Scripting and Coding

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-23-2020 02:48 PM
You will have to iterate through array of this nested JSON like below
var obj = {
"chromeosdevices": [
{
"serialNumber": "F88B473",
"lastSync": "2020-10-25T07:01:21.772Z",
"recentUsers": [
{
"type": "USER_TYPE_MANAGED",
"email": "madeup_name@mail.com"
}
]
},
{
"serialNumber": "5CD13786X9",
"lastSync": "2020-10-14T07:29:47.104Z"
},
{
"serialNumber": "NXHKLED00J08132D917600",
"lastSync": "2020-11-03T10:09:58.319Z",
"recentUsers": [
{
"type": "USER_TYPE_MANAGED",
"email": "madeup_name2@mail.com"
},
{
"type": "USER_TYPE_MANAGED",
"email": "madeup_name3@mail.com"
}
]
}
]
};
for (var key in obj) { // Loop through all the elements in the objects array
var array_element=obj[key];
for (var innerKey in array_element)//For each element, see if it contains key named email
{
if(innerKey == "email"){
var cluster_array = array_element[innerKey];
for (var clusterKey in cluster_array)// Print each element in the Cluster array
{
gs.print(cluster_array[clusterKey]);
}
}
}
}
Regards,
Sachin