user88975
user88975

Reputation: 1648

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

Upvotes: 57

Views: 172054

Answers (4)

Alnitak
Alnitak

Reputation: 339816

That's expected behavior.

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.

Upvotes: 57

Arun
Arun

Reputation: 760

Try this:

s = {"a":"b", "c":["1", "2", "3"]}
JSON.stringify(JSON.stringify(s))

gives the output as

'"{\"a\":\"b\",\"c\":[\"1\",\"2\",\"3\"]}"'

Upvotes: 20

Emre Tapcı
Emre Tapcı

Reputation: 1908

Try

JSON.stringify(s).replace(/\\"/g, '"')

Upvotes: 27

Tom Carchrae
Tom Carchrae

Reputation: 6486

You can avoid that simply by calling JSON.stringify() exactly once on the data you want turn into JSON.

Upvotes: 22

Related Questions