Hello Friends 👋,
Welcome to Infinitbility.
When we stringify JSON multiple times it will add slashes in JSON and that’s why many folks getting these errors.
check the following example.
let users = [
{ id: 1, name: 'Infinitbility', email: 'infinitbility@gmail.com' },
{ id: 2, name: 'notebility', email: 'notebility@gmail.com' },
{ id: 3, name: 'stackbility', email: 'stackbility@gmail.com' },
];
console.log(JSON.stringify(JSON.stringify(users)));
console.log(JSON.stringify(JSON.stringify(JSON.stringify(users))));
Here, I have stringify double and triple times to check their output, and here is the result.
Now, we have to same times parse the string to get actual JSON like the following example.
let users = [
{ id: 1, name: 'Infinitbility', email: 'infinitbility@gmail.com' },
{ id: 2, name: 'notebility', email: 'notebility@gmail.com' },
{ id: 3, name: 'stackbility', email: 'stackbility@gmail.com' },
];
let userStr = JSON.stringify(JSON.stringify(JSON.stringify(users)));
console.log(userStr);
console.log(JSON.parse(JSON.parse(JSON.parse(userStr))));
Output
but when you are an exception, and above solution not working for you.
Replace backslash to nothing in global level
Replace your backslash of every occurrence using the /\\/g
regex and javascript replace method.
After your replace try to parse your string like the following example
let str = "{\n \"taskNames\" : [\n \"01 Jan\", \n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\", \n \"05 Jan\"\n]}"
var finial = str.replace(/\\/g, "");
console.log(JSON.parse(finial));
Output
Thanks for reading…