Skip to content

Instantly share code, notes, and snippets.

@bryanbarnard
Created July 2, 2015 14:57
Show Gist options
  • Save bryanbarnard/3063766969d20edecdd9 to your computer and use it in GitHub Desktop.
Save bryanbarnard/3063766969d20edecdd9 to your computer and use it in GitHub Desktop.
Sample RESTMessageV2 Parse JSON Response
// NOTE: this sample was run in a ServiceNow instance running release version Fuji Patch 4
(function sampleRequest() {
try {
var request = new sn_ws.RESTMessageV2();
request.setHttpMethod('get');
request.setEndpoint('https://rawgit.com/anonymous/f1c4664cafd6caf855fd/raw/f7ca3b022045e2c9f49dd2b453dea0cecc09888c/sample_json.json');
var response = request.execute();
var httpResponseStatus = response.getStatusCode();
var httpResponseContentType = response.getHeader('Content-Type');
var parser = new JSONParser();
var parsed = {};
var httpResponseBody;
gs.print("http response status_code: " + httpResponseStatus);
gs.print("http response content-type: " + httpResponseContentType);
// if request is successful then parse the response body
if (httpResponseStatus == 200 && httpResponseContentType == 'application/json;charset=utf-8') {
httpResponseBody = response.getBody();
// parse JSON string returned from request into a json object
parsed = parser.parse(httpResponseBody);
// iterate over JSON object only printing the id property of JSON objects in results array
for (var i = 0; i < parsed.results.length; i++) {
gs.print('id: ' + parsed.results[i].id)
}
}
}
catch (ex) {
var message = ex.getMessage();
}
})();
@bryanbarnard
Copy link
Author

bryanbarnard commented Nov 13, 2019 via email

@alikrc
Copy link

alikrc commented Feb 17, 2020

@bryanbarnard
missing ";" at 31
"gs.print('id: ' + parsed.results[i].id)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment