How to convert this to JS object:
{"info":["Image has been added"],"success":["No success Sorry!"]}
JSON.parse throws an error and says " isn't valid JSON. Am new to JS and can't figure out how to deal with this.
I am using connect-flash from express to transfer flash messages to the client side. For doing so, I am using the following code:
if Object.keys(locals.flashes).length !== 0
script.
flashArr="#{JSON.stringify(locals.flashes)}"
On the client side, the representation of the Object isn't valid JSON. How can I handle this.
As suggested, you need to parse the HTML entities to characters, i.e. convert "
to "
. The simplest way is to use a regular expression:
var str = '{"info":["Image has been added"],"success":["No success Sorry!"]}';
var obj = JSON.parse(str.replace(/"/g,'"'));
console.log(obj);
Of course if you have other HTML entities in the code it might be better to use the built-in HTML parser:
var str = '{"info":["Image has been added"],"success":["No success Sorry!"]}';
var el = document.createElement('div');
el.innerHTML = str;
var obj = JSON.parse(el.textContent);
console.log(obj);
But for a single entity, replace is likely faster and more efficient.