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

MrMuhammad
Giga Sage

Hi Su,

i am assuming you are recieving your response in variable "response". So, now this how you will parse type and message from the response. 

 

Theory

Response is the object that containing property of type object named "error" which also have two string properties "type" & "message".

You can access object properties in two ways:

objectName.propertyName

or

objectName["propertyName"]
 
 
Practical

var httpStatus = response.getStatusCode(); 

if(httpStatus == '500') { 

     var type = response['error']['type'];

     var message = response['error']['message'];

 }

Now, use type and message variables the way you want. e.g

gs.addInfoMessage(type);

gs.addInfoMessage(message);

 

Please mark this accepted/helpful, if applicable.

 

Thanks & Regards,

Sharjeel

Regards,
Muhammad

Thanks for the response.

The below method is throwing null value.

var type= response['error']['type'];

Can you try below and share me the values you are getting against each log? 

var type;
var message;

var res =  JSON.parse(response.getBody());
var httpStatus = res.getStatusCode(); 

gs.info("Su response - " + res);
gs.info("Su Status- " + httpStatus);

if(httpStatus.toString() == '500') { 

     type = res.type;

     message = res.message;

} else {
    gs.info('Su Else- Inside Else');
}

gs.info("Su type - " + type);

gs.info("Su message - " + message);
Regards,
Muhammad

Didn't get inside the loop.

This is what I am getting.

Couldn't find getStatusCode in object [object Object].