简体   繁体   中英

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

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.

只需在要转换为JSON的数据上调用JSON.stringify()一次就可以避免这种情况。

Try this:

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

gives the output as

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

尝试

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM