How to solve : "Bad control character in string literal in JSON" ?

User205031
Tera Contributor

Hi All,

 

I am trying to pass rejection comments through JSON once the RITM state is rejected.

The JSON payload is :

User205031_0-1762238681792.png

But I am getting the below error in the response body:

 

User205031_1-1762238714559.png

 

How can I solve this issue?

Thanks in advance!

11 REPLIES 11

Ankur Bawiskar
Tera Patron

@User205031 

some invalid character is being transferred and hence the error

just before including comments, strip the invalid characters

see this

JSON encoding - String contains control character 

💡 If my response helped, please mark it as correct ✅ and close the thread 🔒— this helps future readers find the solution faster! 🙏

Ravi Gaurav
Giga Sage

Hi @User205031 
----------------------------

{
"decision": "rejected",
"ritm": "RITM005348616",
"comment": "11/04/2025 01:22:26 AM - Ravi (...) rejectingggggggggggggg\n"
}
Always wrap your JSON in JSON.stringify() rather than manually concatenating strings:
var payload = {
decision: "rejected",
ritm: "RITM005348616",
comment: "Rejected due to missing details"
};
var requestBody = JSON.stringify(payload);
-------------------
If you’re building the JSON dynamically in ServiceNow, use:
var payload = {};
payload.decision = "rejected";
payload.ritm = current.number.toString();
payload.comment = gs.nowDateTime() + " - " + gs.getUserDisplayName() + " (Comments) " + comments.replace(/\r?\n/g, "\\n");
var body = JSON.stringify(payload);

That .replace(/\r?\n/g, "\\n") ensures any line breaks in the comment field are properly escaped before converting to JSON.




Hi @Ravi Gaurav ,

 I have written the below script in the 'Script Step' section:

(function execute(inputs, outputs) {
// ... code ...

var ritmNo = inputs.ritm_no.sys_id;
var stateValue = inputs.state;

var grApproval = new GlideRecord('sysapproval_approver');
    grApproval.addQuery('document_id', ritmNo);
    grApproval.addQuery('state', stateValue); // Filter for rejected approvals
    grApproval.orderByDesc('sys_created_on'); // Get the most recent rejection
    grApproval.query();

    var rejectionComments = '';
    if (grApproval.next()) {
        rejectionComments = grApproval.comments.getJournalEntry(-1); // Get rejection comments
    }

    // Output the rejection comments for use in subsequent flow steps
    outputs.comment = JSON.stringify(rejectionComments);

})(inputs, outputs);
 
The in the REST step, I am passing the request body:
User205031_0-1762245229895.png

How do I modify the code?

 

Thanks!

@User205031 

update as this -> why are you using stringify when you simply want comments text

outputs.comment = rejectionComments;

💡 If my response helped, please mark it as correct ✅ and close the thread 🔒— this helps future readers find the solution faster! 🙏