Logging Raw Rest Data in Scripted Rest API (Inbound)

tchaikin
Giga Expert

I have an inbound scripted REST API I've developed for an integration with another system. This system will be sending transactional data to ServiceNow periodically.

The issue I'm having is that I want to capture the raw JSON from the REST message, as well as parse the data sent into variables which will be used to insert records into a table. I've found that I can't do both, at least not in the way which seems simplest.

var body = request.body;

var tDate = body.data.transactionDate;

As soon as I start pulling data out in the above fashion, the following returns an empty value.

gs.log(request.body.dataString);

If I try to use the dataString before the data object, I can't parse variables out in the manner shown in the first code block.

Does anyone have a (hopefully simple) solution to this requirement? To both save the JSON string sent through the API and to parse the data sent through the API into variables to be used to insert a table record.

1 ACCEPTED SOLUTION

josh_nerius
ServiceNow Employee
ServiceNow Employee

The request stream can only be read once. Dot-walking into request.body.data implicitly reads the body and parses it into an object. When you subsequently try to access the string, it's no longer available. And vice versa if you go for the dataString first. 

Try something like this: 

var requestString = request.body.dataString; 

// Parse it for easy field extraction
var transaction = JSON.parse(requestString); 
var tDate = transaction.transactionDate; 

// Now do something else with the raw string
gs.debug(requestString); 

 

View solution in original post

5 REPLIES 5

Elijah Aromola
Mega Sage

Can't you just store it before you parse it?

sachin_namjoshi
Kilo Patron
Kilo Patron

it should be request.body.data.transactionDate.

you can add log statement to print value

 

Regards,

Sachin

josh_nerius
ServiceNow Employee
ServiceNow Employee

The request stream can only be read once. Dot-walking into request.body.data implicitly reads the body and parses it into an object. When you subsequently try to access the string, it's no longer available. And vice versa if you go for the dataString first. 

Try something like this: 

var requestString = request.body.dataString; 

// Parse it for easy field extraction
var transaction = JSON.parse(requestString); 
var tDate = transaction.transactionDate; 

// Now do something else with the raw string
gs.debug(requestString); 

 

Thanks Josh, that was the piece I wasn't understanding - I hadn't seen anything in the documentation about it only being able to be read once (although I'm sure I was looking in the wrong place).

Your solution works perfectly for our needs!