每次字符串化时,JSON.stringify都会转义双引号 [英] JSON.stringify escapes double quotes every time when stringified

查看:2619
本文介绍了每次字符串化时,JSON.stringify都会转义双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将从Web服务中检索到的JSON对象存储到javascript中的对象。在许多地方,这会得到字符串化(这个obj会经过一些插件,它会对它进行格式化并存储并进行后续处理)并添加多个斜杠。我该如何避免呢?

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.

我尝试使用 replace(/ \\ / g, )但我以此结尾:{a:b,c:[1,2,3]}

I tried to remove slash by using replace(/\\/g,"") but I end with this : ""{"a":"b","c":["1","2","3"]}""

推荐答案

您期望发生什么?

JSON.stringify 在调用已转换为JSON的数据时,不像身份函数。按照设计,它转义引号,反斜杠等。

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.

你需要调用 JSON.parse() 与您调用 JSON.stringify()一样多次,以获取您放入的相同对象。

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.stringify都会转义双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆