Home > Net >  Quotation mark converted into code in string
Quotation mark converted into code in string

Time:06-03

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

{&#34;key&#34;:&#34;value&#34;}

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

  • Related