evkline
evkline

Reputation: 1511

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

I have a NodeJS app that uses EJS templating for injecting variables from the server into the view. I'm having trouble with a particular value, which is an array containing objects whose values may contain an apostrophe. I have to wrap the EJS template string in a single quote when passing to JSON.parse, and as a result the apostrophe gets confused as the end of the string being passed to JSON.parse. I've tried escaping the apostrophe with no luck.

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

Interprets to:

<script>
  // the string is cut off between the first quote & baz's apostrophe
  window.foo = JSON.parse('[{"bar": "baz's lorem ipsum"}]');
</script>

Upvotes: 2

Views: 1863

Answers (1)

stdob--
stdob--

Reputation: 29172

JSON.stringify return a valid JSON text representation of object. You do not need to parse it back:

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

Upvotes: 3

Related Questions