How to extract Data from JSON Payload?

snow_04
Giga Contributor

Hi,

How can we extract data from response coming in JSON format? Like for example as mentioned below:

{"state":2,"httpCode":200,"response":"{\"Ticket\" : \"061cech41hh7e27c86f88b08c8fd2a\",\"StatusCode\" : \"201 Created\",\"Message\" : \"Record Created.\"}"}

Currently what I am doing in background script is as below:

var str = {"state":2,"httpCode":200,"response":"{\"Ticket\" : \"061cech41hh7e27c86f88b08c8fd2a\",\"StatusCode\" : \"201 Created\",\"Message\" : \"Record Created.\"}"};

gs.info(JSON.stringify(str.status));  -- Getting Correct Output as "2".

Can someone please assist on how to extract the elements present within response attribute JSON, like I want to extract objects like "Ticket" , "StatusCode" which are within the Response Object etc.

 

Currently if I do something as below it gives me undefined:

 

gs.info(JSON.stringify(str.response.IncidentId));

 

Kindly assist!!

 

 

17 REPLIES 17

Use one of the parse methods already posted. As David mentions do NOT run toString() on the string received from third party, just pass that string into either of the json parse methods then you can dot-walk to any field in the structure.

Yeah how are you adding the http code? It certainly looks like you're receiving an object from the REST response and converting it to a string value in your obj variable. You should be able to just use  geBody()

var responseBody = response.getBody();
var httpStatus = response.getStatusCode();

var obj={
"status" : "Value(Either setting it to True or False",
"httpCode": httpStatus,
"response" : responseBody 
}

Krishna  Penaka
Tera Expert

 

Hi,

var webService = '<Name of web service>';

 

var command = '<command>';

 

 

 

var restMessage = new sn_ws.RESTMessageV2(webService, command);  

 

var response = restMessage.execute();

 

var responseBody = response.getBody();

 

 

 

 

 

//Here is where you will parse your JSON object

 

//and set field values on the Requested Item

 

var parse = JSON.parse(responseBody);

 

var payload = parse['Payload'];

 

 

 

 

 

for (var i in payload) {

 

if (payload.hasOwnProperty(i)) {

 

var ritm = payload[i]['REQUEST_ID'] + '';

 

var ritmDetails = payload[i];

 

if (ritm != '')

 

updateRITM(ritm,ritmDetails);

 

}

 

}

 

 

 

 

 

function updateRITM(ritm,ritmDetails) {

 

var gr = new GlideRecord('sc_req_item');

 

gr.addQuery('number',ritm);

 

gr.query();

 

if (gr.next()) {

 

//Set field values here

 

// gr.u_call_num = ritmDetails['CALL_NUM'];

 

// gr.u_status = ritmDetails['STATUS'];

 

// gr.u_problem_type = ritmDetails['PROB_TYPE'];

 

// gr.u_work_type = ritmDetails['WORK_TYPE'];

 

// gr.u_prop_id = ritmDetails['PROP_ID'];

 

}

 

}

Regards ,

Krishnateja