The CreatorCon Call for Content is officially open! Get started here.

parsing multiple objects in json response

damiendye
Kilo Contributor

am calling an external json service (nodeping) and am getting an array of my checks back in json

I would like to be able to decode it and loop over my objects to see if I need to create any incidents from the responses and I have been looking for an example of how I could do it but haven't seen anything that does it

here is a sample result

{"20171016-xxxxxxxx":{"_id":"20171016-xxxxxxxx","customer_id":"20171016","label":"whois_IPv4 ","interval":1,"type":"WHOIS","enable":"active","parameters":{"ipv6":false,"whoisserver":"whois.nic.bcd","target":"nic.bcd","contentstring":"whocares: ","threshold":2},"created":1508321676867},"20171017-2ZJOLUNA":{"_id":"20171017-yyyyyyyy","customer_id":"20171017","label":"whois_IPv4_abc ","interval":1,"type":"WHOIS","enable":"active","parameters":{"ipv6":false,"whoisserver":"whois.nic.abc","target":"nic.abc","contentstring":"whocares: ","threshold":2},"created":1508321677305}}

var obj = new JSON().decode(responseBody);   <--- so how does this return the array in a way it can be useful?

gs.print(obj.length); <<- this doesn't work how can I get the array sie and then iterate over a loop

4 REPLIES 4

Gaurav Bajaj
Mega Sage

Hi,


This should give you an array containing 2 objects i believe.


You can then loop in and get individuals object's attribute like customer id.




for(var n in obj){


gs.log(Obj[n].customer_id);


}



Thanks


Gaurav


For my use case, I needed to simply grab a sys_id from another instance based on a query.   Below is what worked for me.   The response will contain an array of results, so you could iterate over it as below.   In my case, I was testing and knew I would only get just the one result, so I could have alternatively just written something like this:   var id = jsonObject.result[0].sys_id.   Your mileage may vary...



var response = restMessage.execute();


var jsonBody =   response.getBody();


var jsonObject = JSON.parse(jsonBody);


var ms_sys_id;


// this loop really only iterates once to grab the result object contained in the wrapping response


for (var key in jsonObject.result) {


    var someObj = jsonObject.result[key];


    ms_sys_id = someObj.sys_id;


}


Thanks Gaurav that got me going



my code looks like and am getting details of the whole response



try {


var r = new sn_ws.RESTMessageV2('Nodeping Checks', 'get');


var response = r.execute();


var responseBody = response.getBody();


var httpStatus = response.getStatusCode();


}


catch(ex) {


var message = ex.getMessage();


}


var jsonObject = JSON.parse(responseBody);



for (var key in jsonObject) {


    var someObj = jsonObject[key];


    gs.print(someObj._id);


    gs.print(someObj.label);


}


Hi Damien,



Are you stuck anywhere now or this has been resolved?



Thanks


Gaurav