Slyknight
Slyknight

Reputation: 131

Can I render JSON.parse data to EJS?

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. :)

Upvotes: 7

Views: 18159

Answers (3)

Dipak
Dipak

Reputation: 6960

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.

Upvotes: 2

Scriptonomy
Scriptonomy

Reputation: 4055

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>

Upvotes: 8

Ethan
Ethan

Reputation: 3798

Try 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: JSON.stringify(str) });
});

You will need to convert your JSON object back to a string before passing it to the template using JSON.stringify, otherwise it will just be rendered with .toString, which returns [object Object],[object Object].

Upvotes: -2

Related Questions