Validate JSON body

Geeky
Kilo Guru

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);
4 REPLIES 4

Balaji Jagannat
Kilo Guru

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

}

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);

Ankur Bawiskar
Tera Patron
Tera Patron

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

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

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.