Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify escapes double quotes every time when stringified

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"]}""

like image 834
user88975 Avatar asked May 12 '13 13:05

user88975


People also ask

Does JSON Stringify escape double quotes?

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.

How do I remove quotes from JSON Stringify?

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);

Does JSON always use double quotes?

JSON names require double quotes.

Is JSON Stringify consistent?

Deterministic version of JSON. stringify() , so you can get a consistent hash from stringified results.


1 Answers

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.

like image 186
Alnitak Avatar answered Oct 14 '22 18:10

Alnitak