Javascript JSON.stringify 无需转义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10967105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.stringify escaping without need
提问by John
JSON.stringify is converting my json object to the following string
JSON.stringify 正在将我的 json 对象转换为以下字符串
{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
When it should not be escaped. The result should be as the string quoted below
当它不应该被逃避时。结果应该是下面引用的字符串
{"2003":{"1":{"2":["test"],"3":["test2"]}}}
{"2003":{"1":{"2":["test"],"3":["test2"]}}}
Rather than use a general replace of all the escaped quotes and remove ones that could be in the input. How can I set JSON.stringify to not double escape the variables?
而不是使用所有转义引号的一般替换并删除可能在输入中的引号。如何将 JSON.stringify 设置为不双重转义变量?
回答by Engineer
You are stringifying a string, not an object:
您正在字符串化一个字符串,而不是一个对象:
var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}';
var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}};
console.log( JSON.stringify(str) ); // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
console.log( JSON.stringify(obj) ); // {"2003":{"1":{"2":["test"],"3":["test2"]}}}