JSON.stringify doesn't escape?

做~自己de王妃 提交于 2019-12-18 03:57:20

问题


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?

This is outputted into the template without any of the quotes being escaped:

{"console":{"free":false}}

回答1:


The quotes around property names are not supposed to be escaped, only quotes inside strings. Your JSON is fine :)




回答2:


It doesn't escape characters, no, there's encodeURIComponent for that, and you can use them together, as in encodeURIComponent(JSON.stringify(obj))




回答3:


stringify the object twice does the trick

console.log(JSON.stringify(JSON.stringify({"console":{"free":false}})));
// "{\"console\":{\"free\":false}}"



回答4:


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)

http://jsfiddle.net/userdude/YVGbH/



来源:https://stackoverflow.com/questions/5506000/json-stringify-doesnt-escape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!