JSON.stringify 没有转义?

发布于 2024-10-28 00:30:28 字数 139 浏览 2 评论 0原文

我正在使用`JSON.stringify?字符串化一个对象,但引号没有转义?我是否误解它应该转义引号?

这将输出到模板中,而不会转义任何引号:

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

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}}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

沫离伤花 2024-11-04 00:30:28

将对象字符串化两次就可以了

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

stringify the object twice does the trick

console.log(JSON.stringify(JSON.stringify({"console":{"free":false}})));
// "{\"console\":{\"free\":false}}"
妖妓 2024-11-04 00:30:28

它不会转义字符,不,有 encodeURIComponent 可以实现这一点,您可以将它们一起使用,如 encodeURIComponent(JSON.stringify(obj))

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

听风吹 2024-11-04 00:30:28

属性名称周围的引号不应转义,只能转义字符串内的引号。你的 JSON 没问题:)

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

芸娘子的小脾气 2024-11-04 00:30:28

如果没有要检查的违规代码,我想知道是否发生了其他事情。作为测试...

<div id="test"/>

var ex = {'test':'This is "text".'};

$('#test').text(JSON.stringify(ex));

输出{"test":"This is \"text\"."} (<注意转义的双引号)

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

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/

未蓝澄海的烟 2024-11-04 00:30:28

这有点旧,但这是我的解决方案

const data = [{"name":"Mechanical2244","description":"Adjustment something..."},{"name":"Electricity","description":"Adjustment something2..."}];
const string = JSON.stringify(data)
        
console.log(string.replace(/"/g, '\\"'));

结果

[{\"name\":\"Mechanical2244\",\"description\":\"Adjustment something...\"},{\"name\":\"Electricity\",\"description\":\"Adjustment something2...\"}]

This is a bit old but here is my solution

const data = [{"name":"Mechanical2244","description":"Adjustment something..."},{"name":"Electricity","description":"Adjustment something2..."}];
const string = JSON.stringify(data)
        
console.log(string.replace(/"/g, '\\"'));

result

[{\"name\":\"Mechanical2244\",\"description\":\"Adjustment something...\"},{\"name\":\"Electricity\",\"description\":\"Adjustment something2...\"}]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文