-1

I am creating api in NodeJS in api response I am getting / this characters Below is my api response:

img

 static async getAdminOrders(logId, callback) {
  
  logger(logId, `Getting all orders of the stylist ${logId}`);
  const queryStr = 'SELECT order_details FROM stylist_order';
  Util.executeQuery(queryStr,logId).then((result) => {
  callback(false, result || [], Util.statusCodes.SUCCESS);
  
  var str = JSON.stringify(result);

  // Remove \ from the string
  var str1 = str.replace(/\\/g,'');

  // Convert updated string back to object
  var newObj = JSON.parse(str1);
  console.log(newObj);

}).catch((error) => {
  logger(logId, error);
  callback(true, { message: 'Failed to fetch order detials' }, Util.statusCodes.INTERNAL_SERVER_ERROR);
});
}

It is not returning object back after removing unwanted characters in console but when I am doing console.log(str1) its returning string without /. Issue is newObj is not showing.

Someone let me know what I am doing wrong.

Digvijay
  • 2,887
  • 3
  • 36
  • 86
  • 2
    Your API JSON.stringifies the data twice. Fix your backend instead of hacking around in the frontend. – Thomas Dec 07 '21 at 17:29
  • Why do you need to replace the characters? It is just escaping the quotes. Just call JSON.parse without trying to replace them. – basic Dec 07 '21 at 17:31
  • Please don't spam StackOverflow with the same exact question to get more attention. https://stackoverflow.com/questions/70270363/eliminate-unwanted-character-from-api-response – Inigo Dec 08 '21 at 06:05

1 Answers1

0

The backslash escapes the " character, so they are not really unwanted. When you just remove them, you could potentially damage the payload, since JSON.parse() can't read the string properly anymore. I would instead try to parse the data string itself like this:

static async getAdminOrders(logId, callback) {
  
  logger(logId, `Getting all orders of the stylist ${logId}`);
  const queryStr = 'SELECT order_details FROM stylist_order';
  Util.executeQuery(queryStr,logId).then((result) => {
  callback(false, result || [], Util.statusCodes.SUCCESS);
  
  for(let i = 0; i < result.data; i++){
    result.data[i].order_details = JSON.parse(result.data[i].order_details)
  }
  
  console.log(result);

}).catch((error) => {
  logger(logId, error);
  callback(true, { message: 'Failed to fetch order detials' }, Util.statusCodes.INTERNAL_SERVER_ERROR);
});
}
koljaa
  • 28
  • 5