I have a use case where an object was passed from server to client through EJS like below:
res.render('mytemplate', {data: myobject});
<script type='text/javascript'>
<% if (typeof data !== 'undefined' && data) { %>
data: '<%= JSON.stringify(data) %>',
<% } %>
</script>
I'm having this issue that in the client code, the returned stringified object looks like
{"key":"value"}
whereas it is supposed to be
{"key":"value"}
So when I do JSON.parse() in the client code I get an error. How do I keep the quotation marks in the string instead of the special character code? Thanks!
CodePudding user response:
I think you need to use the unescaped
way in your template:
data: '<%- JSON.stringify(data) %>',
Note the <%-
instead of <%=
See the documentation "Tags" section: https://ejs.co/#docs