Line breaks in JSON response

Rom
Kilo Contributor

Hi everyone,

I'm using a scripted rest API to pull data from a table in ServiceNow with one of them being a string value from a journal entry. The response is in a JSON format but the string output is displaying line breaks (\n) instead of actual newlines in between. Is it possible to replace these line breaks with new lines in the response? Can a JSON response value even display multiple lines?

Here is a summary of the script I am using:

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {


var bodyList = [];
var x = new GlideRecord('table');
x.addEncodedQuery('query');
x.query();

while(x.next()) {
var body = {};
body.messages = x.getDisplayValue('comments_and_work_notes');
bodyList.push(body);
}

response.setContentType('application/JSON');
response.setBody(bodyList);
var writer = response.getStreamWriter();
writer.writeString(JSON.stringify(bodyList));

})(request, response);

Any feedback on my script is also appreciated. Thanks in advance!

1 ACCEPTED SOLUTION

Omkar Mone
Mega Sage

Hi 

Can you try with the below code?

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

var body = {};
var bodyList = [];
var x = new GlideRecord('table');
x.addEncodedQuery('query');
x.query();

while(x.next()) {
var messageString = x.getDisplayValue('comments_and_work_notes');
body.messages = messageString.toString().replace(/(\r\n|\n|\r)/gm, "");
bodyList.push(body);
}

response.setContentType('application/JSON');
response.setBody(bodyList);
var writer = response.getStreamWriter();
writer.writeString(JSON.stringify(bodyList));

})(request, response);

 

Hope this helps.

 

Regards

Omkar Mone

View solution in original post

3 REPLIES 3

Omkar Mone
Mega Sage

Hi 

Can you try with the below code?

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

var body = {};
var bodyList = [];
var x = new GlideRecord('table');
x.addEncodedQuery('query');
x.query();

while(x.next()) {
var messageString = x.getDisplayValue('comments_and_work_notes');
body.messages = messageString.toString().replace(/(\r\n|\n|\r)/gm, "");
bodyList.push(body);
}

response.setContentType('application/JSON');
response.setBody(bodyList);
var writer = response.getStreamWriter();
writer.writeString(JSON.stringify(bodyList));

})(request, response);

 

Hope this helps.

 

Regards

Omkar Mone

Rom
Kilo Contributor

This did remove the tags, but did not create new lines in place. Instead of replacing it with a blank value, I replaced the characters with <br> tags and this seems to work on the receiving end.

Many thanks Omkar!

Welcome Rom 🙂 

Cheers 🙂