Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

how to get the REST API code

hemantnh
Tera Expert

i am getting the rest api response like below 

 

Response Body: {"id":"dsajnddna","id2":"orn","id3":"orndawdw"}

 

now i want get the id2 value from this body, i am unable to get the id2 value. please help mee

2 REPLIES 2

Sheldon  Swift
ServiceNow Employee
ServiceNow Employee

If your response body is a JSON string:

var responseBody = '{"id":"dsajnddna","id2":"orn","id3":"orndawdw"}';
var obj = JSON.parse(responseBody);

var id2 = obj.id2; // "orn"

 

If your response body is already a JSON object:

var id2 = responseBody.id2;

 

If you need to guard against missing fields:

var id2 = (obj && obj.id2) ? obj.id2 : null;

 

k_lutz
Tera Guru

Hi,

This is assuming you are not looping through a list of these and just the response body you showed above, but you could try something like:

 

var response = r.execute();

var responseBody = response.getBody();

var httpStatus = response.getStatusCode();

 

// Parse the JSON response

var jsonResponse = JSON.parse(responseBody);

 

// Extract values into variables

var id = jsonResponse.id;

var id2 = jsonResponse.id2;

var id3 = jsonResponse.id3;

gs.info('ID: ' + id + ', ID2: ' + id2 + ', ID3: ' + id3);