Javascript JSON.stringify 没有转义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5506000/
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 doesn't escape?
提问by Harry
I'm using `JSON.stringify? to stringify an object, but the quotes are not escaped? Am I misunderstanding that it's suppose to escape the quotes?
我正在使用`JSON.stringify?字符串化一个对象,但引号没有转义?我是否误解了它应该逃避引号?
This is outputted into the template without any of the quotes being escaped:
这被输出到模板中,没有任何引号被转义:
{"console":{"free":false}}
采纳答案by Ricardo Tomasi
The quotes around property names are not supposed to be escaped, only quotes inside strings. Your JSON is fine :)
不应转义属性名称周围的引号,只能转义字符串内的引号。你的 JSON 很好 :)
回答by Jim Blackler
It doesn't escape characters, no, there's encodeURIComponent
for that, and you can use them together, as in encodeURIComponent(JSON.stringify(obj))
它不会转义字符,不,是encodeURIComponent
为了那个,你可以一起使用它们,如encodeURIComponent(JSON.stringify(obj))
回答by Nerdroid
stringify the object twice does the trick
将对象字符串化两次就行了
console.log(JSON.stringify(JSON.stringify({"console":{"free":false}})));
// "{\"console\":{\"free\":false}}"
回答by Jared Farrish
Without the offending code to inspect, I'm wondering if something else is happening. As a test...
没有要检查的违规代码,我想知道是否发生了其他事情。作为测试...
<div id="test"/>
var ex = {'test':'This is "text".'};
$('#test').text(JSON.stringify(ex));
Outputs: {"test":"This is \"text\"."}
(< Note the escaped double quotes)
输出:{"test":"This is \"text\"."}
(< 注意转义的双引号)