We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

Handling Special Characters in Scripted REST API Payload

Priya3
Tera Contributor

Hi,
I have created a Scripted REST API to generate requests in ServiceNow. However, when special characters are passed in the payload, the field values are stored as encoded entities such as à, ', &, etc.
Currently, I am using the following logic:
var RequestBody = request.body;
var RequestData = RequestBody.data;
var strREQ = JSON.stringify(RequestData);
var parser = new JSONParser();
var result = parser.parse(strREQ);
for (var key in result) {
if (key != 'att_data' && result[key] && typeof result[key] === 'string') {
result[key] = GlideStringUtil.unEscapeHTML(result[key]);
}
}
This approach is able to decode basic HTML entities like &, but it does not handle numeric character references such as à or '.
Could you please advise on the best approach to decode these numeric values in ServiceNow?
Thanks,

5 REPLIES 5

palanikumar
Giga Sage

Hi @Priya3 

 

You can try this

 

var RequestBody = request.body;
var RequestData = RequestBody.data;
var strREQ = JSON.stringify(RequestData);
var parser = new JSONParser();
var result = parser.parse(strREQ);
for (var key in result) {
  if (key != 'att_data' && result[key] && typeof result[key] === 'string') {
    result[key] = decodeHTML(result[key]);
  }
}

function decodeHTML(encodedString) {
    return (j2js(new GlideStringUtil().unEscapeHTML(encodedString))).replace(/&#x{0,1}([0-9a-fA-F]+);/gi, function(match, numStr) {
		gs.info(numStr.toString());
        var num = parseInt("0x" + numStr.toString());
        return String.fromCharCode(num);
    });
}

 

Thank you,
Palani