How to extract data from array within Response Body

cstone
Tera Contributor

Hello Everyone - 

I'm relatively new to ServiceNow Development and scripting in general.  Learning as I go so to speak.

We are setting up an integration with a 3rd party application using outbound REST Messages.

In general it is going well, but there is one part giving me the run around and I was hoping someone here could offer some advice.

I am trying to capture a value from the Response Body and feed it into a custom field on our incident table, something I have done before successfully, but this time I am having issues getting to the data

Here is the relevant part of my script in the business Rule:

var response = r.execute();
var json = response.getBody();
var obj = JSON.parse(json);
var targetNumber = obj.items.ticketId; // the line causing my headaches
current.u_external_ticket_number = targetNumber;
current.u_integration_name = "Example";
current.update();

The "Integration Name" field is being set correctly, but I get nothing in the "External Ticket Number" field.

The response body is:

{"items":[{"ticketId":6276389,"inventoryId":11748563,"wtn":"2125551212","errorMessage":"Error Message Would Show Here","errorCode":409}]}

I imagine its the [ ] causing an issue with the parsing.  An array inside an object?  Not something I have had to work through until now.

Could someone point me in the right direction on how to pull "ticketId" out of the "items" object as a string to feed into the "u_external_ticket_number" field?

1 ACCEPTED SOLUTION

Pradeep Sharma
ServiceNow Employee

Hi, Below please find updated code.

Note: Untested code.

var response = r.execute();
var obj = response.getBody();

var str = JSON.stringify(obj);

var parser = new JSONParser();

var result = parser.parse(str);

var targetNumber = result.items[0].ticketId; 
current.u_external_ticket_number = targetNumber;
current.u_integration_name = "Example";
current.update();

View solution in original post

5 REPLIES 5

Hitoshi Ozawa
Giga Sage

As others have replied, the name "items" suggests there may have several tickets. As such, it may be better to loop through array items.

var response = r.execute();
var json = response.getBody();
var obj = JSON.parse(json);
//var targetNumber = obj.items.ticketId; // the line causing my headaches
var items = obj.items;
for (var i=0; i<items.length; i++) {
  current.u_external_ticket_number = items[i].ticketId;
  current.u_integration_name = "Example";
  current.update();
}