How to parse response body?

tyagisu
Mega Expert

Hi,

My requirement is to get the message and type from the response body. When I get status code 500, this is the response body I have. I am using the script include for calling the rest API and then calling this API in one of the UI actions. So I need to show this message and type I get in my response body when I click the UI action.

ResponseBody:

{
"error" : {
"type" : "SERVICE_EXCEPTION",
"message" : "MTA may be in use and determined to be not safe to suspend."
}
}

Any help would be appreciated!

Thanks,

Su

1 ACCEPTED SOLUTION

Cool. Can you now replace 

type = res.type;

message = res.message;

with 

type = res.error.type;

message = res.error.message;
Regards,
Muhammad

View solution in original post

17 REPLIES 17

Ct111
Tera Sage

Hi, Check the below example where parsing has been explained.

https://developer.servicenow.com/dev.do#!/learn/learning-plans/orlando/servicenow_application_developer/app_store_learnv2_rest_orlando_exercise_parse_rest_response

 

Mark my Answer as Correct and Helpful if it helps

Thanks for your response.

My client is using New York. The above solution is for Orlando I think, I couldn't find the application.

Thanks,

Su

Satyanarayana C
ServiceNow Employee
ServiceNow Employee

Hi,

There are two things to remember here:

1. When you send a response from Server, you should always send as a string.

    So, before returning the response convert it to a string using JSON.stringify('<response>');

2. The place where you are reading the response:

    Convert the response to a JSON using JSON.parse('<response>');

3. Once you do the above two steps:

    You need to handle the response JSON. You can read it like shown below:

    var response = JSON.parse(responseBody);

    if(response.error) {

      var errorType = response.type;

      var errorMessage = response.message;

    }

Thanks

 

Hi Satya,

Thanks for your response. The below solution didn't work. Can you please let me know what did I miss?

var jsonObj = JSON.stringify(responseBody);
var res = JSON.parse(jsonObj);
if (res.error) {
gs.info("Inside if:" + res.error);
type = res.type;
message = res.message;

gs.info("Type:" + type);
}

Thanks,

Su

Prasant Kumar 1
Kilo Sage

Hi,

You can follow the below script:-


var r = new sn_ws.RESTMessageV2('Get Data', 'Default GET');

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

gs.print(responseBody);
gs.log("response body is" + responseBody);
var obj = JSON.parse(responseBody);

 

If i was able to solve your query, please mark my answer correct and helpful.

Thanks & Regards

Prasant kumar sahu