Not able to parse XML to JSON --Getting error as Unexpected Token:o

Ankur Khare
Tera Contributor

HI Team,

 

Below is sample code which is written in After Business Rule. I believe the issue is from line no 35 to line no 38 is not printing anything. I believe XML to JSON conversion is the issue.

In my try catch block I am getting error as "Unexpected Token o".

 

Attached is the sample code in notepad .If you see the catch block I am getting error as Unexpected Token o


         AnkurKhare_0-1722271967707.png

 

1 ACCEPTED SOLUTION

Hi @Ankur Khare 

please make the below changes:

 

 

// Parse JSON string back to an object
    var objHandle = JSON.parse(jsonString);
    gs.log('objHandle: ' + JSON.stringify(objHandle)); // Log objHandle for debugging
    
    // Access and log specific properties
    if (objHandle.net) {
        gs.log('parentNetHandle: ' + objHandle.net.parentNetHandle);
    } else {
        gs.log('The "net" property does not exist in the JSON object.');
    }

 

 

 

 

…………………………………………........................................................................................
Mark it helpful 👍and Accept Solution !! If this helps you to understand.

…………………………………………........................................................................................

View solution in original post

5 REPLIES 5

Akshay Gupta2
Kilo Sage

Hi @Ankur Khare ,

 

Can you please once try to log before parsing response.

 

The error "Unexpected Token o" typically occurs when JSON.parse() is trying to parse a string that is not a valid JSON. In your code, this could be happening because the gs.xmlToJSON(responseBody) function might not be returning a string that can be parsed by JSON.parse().

Here are a few things you can do to troubleshoot and fix this issue:

  1. Check the output of gs.xmlToJSON(responseBody): Ensure that it is indeed returning a JSON string and not some other object or string that JSON.parse cannot handle.
  2. Directly log the output of gs.xmlToJSON(responseBody): This will help you understand what is being returned.

 

Example - 

 

var response = "<note>"+
"<to>Tove</to>"+
"<from>Jani</from>"+
"<heading>Reminder</heading>"+
"<body>Don't forget me this weekend!</body>"+
"</note>";

var ans = gs.xmlToJSON(response);

gs.log(ans.note.to); // result - Tove
 
I believe you do not need to parse json again.
 
Please give a thumbsup and mark as solution.
 
Thanks
Akshay