在作为 EJS 模板传递以查看的字符串化 JSON 中转义单引号
Escaping single quotes in stringified JSON thats passed as EJS template to view
我有一个 NodeJS 应用程序,它使用 EJS 模板将变量从服务器注入到视图中。我在处理特定值时遇到问题,该值是一个包含对象的数组,其值可能包含撇号。传递给 JSON.parse 时,我必须将 EJS 模板字符串用单引号括起来,结果,撇号被混淆为传递给 JSON.parse 的字符串的末尾。我试过转义撇号但没有成功。
<script>
window.foo = JSON.parse('<%- JSON.stringify([{"bar": "baz's lorem ipsum"}]) %>');
</script>
解释为:
<script>
// the string is cut off between the first quote & baz's apostrophe
window.foo = JSON.parse('[{"bar": "baz's lorem ipsum"}]');
</script>
JSON.stringify
return 对象的有效 JSON 文本表示。你不需要解析它:
<script>
window.foo = <%- JSON.stringify([{"bar": "baz's lorem ipsum"}]) %>;
</script>
我有一个 NodeJS 应用程序,它使用 EJS 模板将变量从服务器注入到视图中。我在处理特定值时遇到问题,该值是一个包含对象的数组,其值可能包含撇号。传递给 JSON.parse 时,我必须将 EJS 模板字符串用单引号括起来,结果,撇号被混淆为传递给 JSON.parse 的字符串的末尾。我试过转义撇号但没有成功。
<script>
window.foo = JSON.parse('<%- JSON.stringify([{"bar": "baz's lorem ipsum"}]) %>');
</script>
解释为:
<script>
// the string is cut off between the first quote & baz's apostrophe
window.foo = JSON.parse('[{"bar": "baz's lorem ipsum"}]');
</script>
JSON.stringify
return 对象的有效 JSON 文本表示。你不需要解析它:
<script>
window.foo = <%- JSON.stringify([{"bar": "baz's lorem ipsum"}]) %>;
</script>