【问题标题】:Escaping single quotes in stringified JSON thats passed as EJS template to view在作为 EJS 模板传递以查看的字符串化 JSON 中转义单引号
【发布时间】:2016-06-26 02:33:33
【问题描述】:

我有一个 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>

【问题讨论】:

  • 我们说的是服务器代码还是客户端代码?目前尚不清楚您要达到的目标。顺便说一句,单引号应该被转义。

标签: javascript json node.js ejs


【解决方案1】:

JSON.stringify 返回对象的有效 JSON 文本表示。您不需要将其解析回来:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多