Failed to parse JSON data error.

rohit_murli
Tera Contributor

Hello,

We are integrating ServiceNow with an external platform. When a form is submitted on the external platform, an RITM ticket should be generated in ServiceNow, and all form details should be added to the RITM variables.

 

Currently, I'm using the JSON.parse method, and when I send the raw JSON data, I receive the following error:

bindu_jayagond_0-1696244482110.png


I used stringyfy method yet received similar 'Failed to parse JSON data error'. 

 

Any kind of help will be appreciated. 

Thank you.

1 ACCEPTED SOLUTION

@rohit_murli On the following line

jsonData = JSON.parse(requestBody.data);

Here requestBody.data already provides an object hence no parsing is needed here.

Update the code as follows.

jsonData = requestBody.data;
gs.info("Parsed JSON Data: " + JSON.stringify(jsonData));

With the above mentioned changes please check if the logs print the JSON.

View solution in original post

4 REPLIES 4

Sandeep Rajput
Tera Patron
Tera Patron

@rohit_murli Did you try logging the JSON payload while using stringify method 

gs.info(JSON.stringify(jsonData));

and checked if it generated the JSON correctly in the logs. 

Hello @Sandeep Rajput ,

 

Yes please check the below image, 

bindu_jayagond_0-1696252605800.png

I added the stringify method but nothing was printed in the logs. 

Here's the script. Please check and let me know if i'm something wrong :

(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
    try {
        var requestHeaders = request.headers;
        var contentType = requestHeaders['Content-Type'];
        var requestBody = request.body;
        if (!requestBody) {
            throw new Error("Request body is empty.");
        }

        var jsonData;
        try {
            jsonData = requestBody.data;
            gs.info("Parsed JSON Data: " + JSON.stringify(jsonData));
        } catch (jsonError) {
            gs.error("JSON Parsing Error: " + jsonError.toString());
            throw new Error("Failed to parse JSON data.");
        }

 

 


 

@rohit_murli On the following line

jsonData = JSON.parse(requestBody.data);

Here requestBody.data already provides an object hence no parsing is needed here.

Update the code as follows.

jsonData = requestBody.data;
gs.info("Parsed JSON Data: " + JSON.stringify(jsonData));

With the above mentioned changes please check if the logs print the JSON.

Thank you @Sandeep Rajput .

This worked.