Trouble with parsing JSON result from REST

truzicki
Kilo Expert

Hi, everyone.  I'm hoping y'all can help me.  I'm calling an outbound REST message through a business rule to another ServiceNow instance (a vendor's instance) using the Table API.  That part is working fine.  I've set the application type as JSON, and I've confirmed it's set correctly by examining the header's Content-Type.  I'm getting results back, but when I try to parse them using the JSON parser, the whole thing stops working (even the REST call itself).  I created a fix script to try to figure it out, and here's what I've got (I'm manually setting the response here, but it's a trimmed down version of what I'm getting back from the REST message):

var response = '{"result":{"number":"CS0005834","state":"1","case":"CS0005834","impact":"2","active":"true"}}';

var parser = new JSONParser();
var parsedResponse = parser.parse(response);

gs.print('response: ' + response);
gs.print('parsedResponse: ' + parsedResponse.result);
gs.print('parsedResponse.number: ' + parsedResponse.result[0].number);

I just need the number -- but I it's coming back as undefined.  What am I doing wrong?  And, any idea why adding the parsing code would make the REST call fail?

1 ACCEPTED SOLUTION

Inactive_Us1474
Giga Guru

Here it is for the sample :

var response = '{"result":{"number":"CS0005834","state":"1","case":"CS0005834","impact":"2","active":"true"}}';

var parsedResponse = JSON.parse(response);

gs.print('response: ' + response);
gs.print('parsedResponse: ' + parsedResponse.result);
gs.print('parsedResponse.number: ' + parsedResponse.result.number);

 

You can also utilize for the actual response.

View solution in original post

6 REPLIES 6

Inactive_Us1474
Giga Guru

Here it is for the sample :

var response = '{"result":{"number":"CS0005834","state":"1","case":"CS0005834","impact":"2","active":"true"}}';

var parsedResponse = JSON.parse(response);

gs.print('response: ' + response);
gs.print('parsedResponse: ' + parsedResponse.result);
gs.print('parsedResponse.number: ' + parsedResponse.result.number);

 

You can also utilize for the actual response.

truzicki
Kilo Expert


Thank you, Akhil -- much appreciated.  Now my fix script is working perfectly, but any thoughts as to why the business rule stops functioning when I parse the JSON?  

As your script throws exception because of your script issue, it breaks the BR from executing properly. You can check the system logs for error messages

The script execution does not stop by having an undefined value if your script contains the invalid syntax of ECMA it will throw a warning message and stops the execution.