Validate JSON body
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-16-2020 05:36 AM
Hi All,
I have below code in my scripted REST API. But in case if there is comma missing or some invalid format, system should generate error. How can I handle it? JSON.parse is not generating any error messages in try-catch blocks.
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
try {
var myRequest = request.body.dataString;
var obj = new global.JSON().decode(myRequest);
var output = new createCase().create(obj);
return output;
} catch (ex) {
return ex.message;
}
})(request, response);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-16-2020 07:01 AM
can you have this in your try block?
var parser = new global.JSONParser();
var parsedData = parser.parse(request.body.dataString);
if(parsedData.length >0){
//rest of your code to process
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-16-2020 08:16 AM
I am using the below code. How can I check in this?
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
try {
var myRequest = request.body.dataString;
var obj = new global.JSON().decode(myRequest);
var output = new createCase().create(obj);
return output;
} catch (ex) {
return ex.message;
}
})(request, response);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-16-2020 07:02 AM
Hi,
you can use JSON.parse to know whether the incoming string is valid json string or not
So the above script looks good
Mark ✅ Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-16-2020 07:45 AM
Hi Ankur,
I have updated my script above and now not using JSON.parse. If I am using JSON.parse, in the above code, system is giving me error.