转义字符串化 JSON 中的单引号,作为 EJS 模板传递以供查看

Escaping single quotes in stringified JSON thats passed as EJS template to view

本文关键字:EJS 作为 字符串 转义字符 JSON 单引号 转义      更新时间:2023-09-26

我有一个 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返回对象的有效 JSON 文本表示形式。您不需要解析它:

<script>
  window.foo = <%- JSON.stringify([{"bar": "baz's lorem ipsum"}]) %>;
</script>