问题
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