The CreatorCon Call for Content is officially open! Get started here.

JSON parsing problem

David Christian
Kilo Guru

I'm having a problem with parsing the result of a web service.   the variable "result" is defined earlier in the code.   If i remove the two lines about parsing then everything works, except I can't get the data I need out of the response.   Here is my code:

try {

  var r = new sn_ws.RESTMessageV2('ittools', 'get');

  r.setStringParameter('group_name', result);

  var response = r.execute();

  var responseBody = response.getBody();

  var httpStatus = response.getStatusCode();

}

catch(ex) {

  var message = ex.getMessage();

}

gs.addInfoMessage("Finished REST Message" + response);

var parser = new JSONParser();

var parsed = parser.jsonParse(response);

//gs.addInfoMessage("Finished Parsing" + parsed.Owners[0].UserNames.UTTyler);

And here is the error that I get:

Caught exception in InterpretedScript <refname>: org.mozilla.javascript.InterpretedScriptException: Caught exception in InterpretedScript <refname>: org.mozilla.javascript.InterpretedScriptException: Caught exception in InterpretedScript <refname>: org.mozilla.javascript.JavaScriptException: org.mozilla.javascript.WrappedException: WrappedException of The undefined value has no properties.

1 ACCEPTED SOLUTION

I had a two different ways that worked.   However, it also greatly depends on how the response if formatted as to which way works.   At first our response had characters in it that the ServiceNow parser didn't like but would work on any other standard JSON parser you try on the web.   Due to those characters I had to decode it first then parse it.   I would love to know if one of these ways helped you.



Here the first that worked for me:


var parser = new global.JSON();


var parsed = parser.decode(responseBody);


var mydata = JSON.parse(parsed);



After a change to how the object was sent back to me I was able to use a single line:


var mydata = JSON.parse(responseBody);


View solution in original post

7 REPLIES 7

Hi David,



Thanks for you reply.   We stumbled across a few other threads after my post and were able to resolve our issue by basically implementing the same code fix you have above.  



Thanks again.




On Fuji Patch 9, below is what worked for me -



var parser = new global.JSON();


var parsed = parser.decode(responseBody);


gs.log('REST data parsed: ' + parsed.result[0].name + ', ' + parsed.result[1].name);



Displaying 'parsed' gave '[object Object]'. Third line above fixed this to the output needed.


Awesome!!   I'll have to look into that once we go to Patch 9. For me right now the decoder does not create an object.   It just puts in a format that the parser likes.