1

I am trying to pass a JSON array formed on the backend using node.js to a frontend template so that it can be manipulated by a user. However, I'm having some trouble doing this. Here's the code I am using to render the page:

res.render('pages/profile.ejs', {
                user : doc // get the user out of session and pass to template
                ,passArray: JSON.stringify(passArray)
            });

Then in the scripts for the profile on the frontend I have:

<script>
        var passArrayFull= <%=passArray%>];  
        //do stuff with passArrayFull
        console.log(passArrayFull);
</script>

The problem is that I get that SyntaxError from the frontend site, and when I look at the source to inspect passArray it looks like this:

[{&#34;unit&#34;:&#34;B1&#34;,&#34;name&#34;: 

(etc)

So it looks like somehow the JSON.stringify is converting the " character to the HTML entity &#34 and it's not converting back, even if I wrap the frontend in JSON.parse(). I tried not using JSON.stringify, but then it seems like the full array can't be passed (I get a different error). What am I doing wrong here?

garson
  • 1,505
  • 3
  • 22
  • 56
  • 1
    `JSON.stringify()` is not doing that, but you're right that *something* is doing it. It would suspect that it's the express code in `[<%= passArray %>]`. – Pointy Nov 08 '19 at 16:47
  • 1
    Ah, that helped me figure it out. I had to make it <%-passArray%> instead of <%=. See https://stackoverflow.com/questions/7415641/cradle-express-ejs-convert-html-to-its-entities#7416274 – garson Nov 08 '19 at 16:55

0 Answers0