top of page
SAASWITHSERVICENOW

How to parse a JSON response in ServiceNow?

In ServiceNow, parsing a JSON response involves using the JSON.parse() function to convert the JSON data into a JavaScript object.


Here's an example code snippet:



// JSON response string
var response = '[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]';
// Parse the response string into a JavaScript object
var data = JSON.parse(response);
// Iterate over the data object and log each element's name property
for (var i = 0; i < data.length; i++) {
  gs.info(data[i].name);
}

In this example, the response variable contains a JSON string that represents an array of objects with id and name properties. The JSON.parse() function is called to convert this JSON string into a JavaScript object, which is then stored in the data variable.


The for loop iterates over the data array and logs each element's name property using the gs.info() method.


It's important to note that if the JSON response is not well-formed (e.g., missing quotes or curly braces), the JSON.parse() function will throw a syntax error. In addition, if the JSON response contains sensitive information (e.g., passwords), it's important to handle it appropriately (e.g., redacting the sensitive data) before logging or displaying it.


Example with ServiceNow Data in Response


Here is an example of parsing a JSON response containing incident data from another ServiceNow instance:


var restMessage = new sn_ws.RESTMessageV2();
restMessage.setEndpoint("https://your-instance.service-now.com/api/now/table/incident");
restMessage.setHttpMethod("get");
restMessage.setRequestHeader("Accept", "application/json");
restMessage.setRequestHeader("Content-Type", "application/json");
restMessage.setRequestHeader("Authorization", "Basic " + Glideapp.parseBase64("your_username:your_password"));
restMessage.setQueryParameter("sysparm_limit", "10");

var response = restMessage.execute();
var responseBody = response.getBody();

if (response.getStatusCode() == 200) {
  var data = JSON.parse(responseBody);
  for (var i = 0; i < data.result.length; i++) {
    var incident = data.result[i];
    gs.info("Incident " + incident.number + ": " + incident.short_description);
  }
} else {
  gs.error("Failed to retrieve incident data: " + response.getErrorMessage());
}

Lets understand each section of code:


In this line, we create a new instance of the sn_ws.RESTMessageV2 class, which is used to construct and send HTTP requests to external APIs.


var restMessage = new sn_ws.RESTMessageV2();

Next, we set the endpoint URL for the REST message, which is the URL of the remote ServiceNow instance's incident table API.


restMessage.setEndpoint("https://your-instance.service-now.com/api/now/table/incident");

Next line sets the HTTP method for the REST message to "get", indicating that we want to retrieve data from the remote ServiceNow instance.

restMessage.setHttpMethod("get");

These following lines set the request headers for the REST message. The "Accept" header specifies that we expect a JSON response from the remote ServiceNow instance, while the "Content-Type" header specifies that the request body (which is empty in this case) is also in JSON format.


restMessage.setRequestHeader("Accept", "application/json");
restMessage.setRequestHeader("Content-Type", "application/json");

This following line sets the "Authorization" header for the REST message, which is used to authenticate with the remote ServiceNow instance's incident table API using Basic Authentication. The username and password are concatenated as a string and Base64-encoded using the Glideapp.parseBase64() method.


restMessage.setRequestHeader("Authorization", "Basic " + Glideapp.parseBase64("your_username:your_password"));

In next line, we set a query parameter for the REST message to limit the number of incidents returned to 10.

restMessage.setQueryParameter("sysparm_limit", "10");

This line executes the REST message and stores the response in a variable called `response`.


var response = restMessage.execute();

Here, we extract the response body from the response variable and store it in a variable called responseBody. The response body is a string representation of the JSON response.

var responseBody = response.getBody();

This line checks if the response status code is 200 (i.e., successful).

if (response.getStatusCode() == 200) {

If the response status code is 200, we parse the response body into a JavaScript object using the JSON.parse() method and store it in a variable called data.


var data = JSON.parse(responseBody);

Here, we loop through the array of incident objects in the data variable and log each incident's number and short description using the gs.info() method.

for (var i = 0; i < data.result.length; i++) {
  var incident = data.result[i];
  gs.info("Incident " + incident.number + ": " + incident.short_description);
}

If the response status code is not 200, we log an error message using the gs.error() method, which includes the error message obtained from response.getErrorMessage().

} else {
  gs.error("Failed to retrieve incident data: " + response.getErrorMessage());
}

Example with JIRA Data in Response


Here is an example of how to use the sn_ws.RESTMessageV2 API to retrieve data from a Jira instance using its REST API and parse the response:



var restMessage = new sn_ws.RESTMessageV2();
restMessage.setEndpoint("https://your-jira-instance.com/rest/api/2/search");
restMessage.setHttpMethod("get");
restMessage.setRequestHeader("Accept", "application/json");
restMessage.setRequestHeader("Content-Type", "application/json");
restMessage.setRequestHeader("Authorization", "Basic " + Glideapp.parseBase64("your_jira_username:your_jira_password"));
restMessage.setQueryParameter("jql", "project = YOUR-PROJECT-KEY");
restMessage.setQueryParameter("maxResults", "10");

var response = restMessage.execute();
var responseBody = response.getBody();

if (response.getStatusCode() == 200) {
  var data = JSON.parse(responseBody);
  for (var i = 0; i < data.issues.length; i++) {
    var issue = data.issues[i];
    gs.info("Issue " + issue.key + ": " + issue.fields.summary);
  }
} else {
  gs.error("Failed to retrieve Jira issue data: " + response.getErrorMessage());
}

In this example, we first create a new instance of the sn_ws.RESTMessageV2 class. We set the endpoint to the Jira instance's search API endpoint, set the HTTP method to "get", and add the necessary headers for authentication and response type.


We also add query parameters to filter the results by project and limit the number of results returned.


We then execute the REST message using the `execute()` method and get the response body using getBody(). If the response status code is 200 (i.e., successful), we parse the response body into a JavaScript object using JSON.parse() and loop through the array of issues to log each issue's key and summary using gs.info().


If the response status code is not 200, we log an error message with the response.getErrorMessage() method.


Note that in this example, we're using a Basic Authentication scheme to authenticate with the Jira instance. This method is not recommended for production use, as it exposes the username and password in clear text. Instead, consider using OAuth or other secure authentication methods.


Here is an example video as well



Recent Posts

See All

Comentários

Não foi possível carregar comentários
Parece que houve um problema técnico. Tente reconectar ou atualizar a página.
Post: Blog2_Post
bottom of page