Handling Special Characters in Scripted REST API Payload
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
3 weeks ago
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,
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
3 weeks ago
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);
});
}
Palani
