I am storing JSON objects retreived from web service to objects in javascript. In many places this gets stringified(This obj goes through some plugins and it strigifies and stores it and retreives it) and it adds multiple slashes. How can I avoid it ?
http://jsfiddle.net/MJDYv/2/
var obj = {"a":"b", "c":["1", "2", "3"]}; var s = ""; console.log(obj); s = JSON.stringify(obj); alert(s); // Proper String s = JSON.stringify(s); alert(s); // Extra slash added, Quotes are escaped s = JSON.stringify(s); alert(s); // Again quotes escaped or slash escaped but one more slash gets added var obj2 = JSON.parse(s); console.log(obj2); // Still a String with one less slash, not a JSON object !
So when parsing this multiple string I end up with a string again. And when tried to access like an object it crashes.
I tried to remove slash by using replace(/\\/g,"")
but I end with this : ""{"a":"b","c":["1","2","3"]}""
JSON. stringify does not act like an "identity" function when called on data that has already been converted to JSON. By design, it will escape quote marks, backslashes, etc.
That makes the regex to remove the quotes from the keys MUCH easier. Start your solution with this: var cleaned = JSON. stringify(x, null, 2);
JSON names require double quotes.
Deterministic version of JSON. stringify() , so you can get a consistent hash from stringified results.
What did you expect to happen?
JSON.stringify
does not act like an "identity" function when called on data that has already been converted to JSON. By design, it will escape quote marks, backslashes, etc.
You need to call JSON.parse()
exactly as many times as you called JSON.stringify()
to get back the same object you put in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With