Can I render JSON.parse data to EJS?

13,269

Solution 1

You are attempting to print an array containing two objects to the ejs template. In a template you only print strings.

To print an object to the template we first need to stringify it:

<%= JSON.stringify(str) %>

To access a property of the object in your array we reference the array index and the property key:

<%= str[0].name %>

To iterate over the array and print out all the values we use a forEach:

<ul>
    <% str.forEach(function(o) { %>
        <li><%= o.name %> - <%= o.age %></li>
    <% }); %>
</ul>

Solution 2

In ejs template we can render json object as below:

<%- JSON.stringify(user) %>

I tried with <%= JSON.stringify(user) %> (<%=) but it will print asci code values for double-quotes.

Share:
13,269

Related videos on Youtube

Slyknight
Author by

Slyknight

Updated on June 04, 2022

Comments

  • Slyknight
    Slyknight almost 2 years

    I am new to NodeJS and Express (to coding, in general). I am trying to render data to an EJS view page so I can manipulate it in the front end. It looks something like this:

    app.set('view engine','ejs');
    var str = JSON.parse('[{"name":"bill", "age":"26"}, {"name":"jeff", "age":"32"}]');
    
    str.forEach(function(data){
        console.log(data.name);
    });
    
    app.get('/data', function(req, res){
        res.render('data', {str:str});
    });
    

    I try to test it in the EJS file by typing in <%= data %> the output I am getting in the browser is [object Object],[object Object]. I feel like I am missing a few piece. Can someone please help me out?

    Thanks

    Edit: Thanks Booligoosh. Just want to add that I had to convert it back to JSON in the EJS side afterward to make it work. :)

  • Cesare
    Cesare over 4 years
    How can you iterative over a string? If str is a string, I'm not sure how you're able to call forEach on it.