55

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

user88975
  • 1,618
  • 3
  • 19
  • 29

4 Answers4

56

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.

Slothario
  • 2,830
  • 3
  • 31
  • 47
Alnitak
  • 334,560
  • 70
  • 407
  • 495
25

Try

JSON.stringify(s).replace(/\\"/g, '"')
Emre Tapcı
  • 1,743
  • 17
  • 16
20

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

leymannx
  • 5,138
  • 5
  • 45
  • 48
Tom Carchrae
  • 6,398
  • 2
  • 37
  • 36
  • Yes, but the original string goes through a series of function calls (in some plugins) and finally when its returned am not sure how many times it got stringified. – user88975 May 12 '13 at 14:27
  • 11
    don't ever stringify it until you need to. until then, just add data to a javascript 'result' object. – Tom Carchrae May 13 '13 at 05:02
12

Try this:

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

gives the output as

'"{\"a\":\"b\",\"c\":[\"1\",\"2\",\"3\"]}"'
Arun
  • 651
  • 2
  • 7
  • 21