0

I'm trying to send JSON-object form MongoDB to page with ejs template engine. Here's the response form my DB (a JSON-object):

"suppliers": [
    {
        "lastname": "lastname1",
        "firstname": "firstname1",
        "middlename": "middlename1",
        "mobtel": "mobtel1",
        "worktel": "worktel1",
        "email": "email1"
    },
    {
        "lastname": "lastname2",
        "firstname": "firstname2",
        "middlename": "middlename2",
        "mobtel": "mobtel2",
        "worktel": "worktel2",
        "email": "email2"
    }
]

As I get i from DB as an object, I have to stringify it to str to send as a var for EJS Template engine:

var myJSONText = JSON.stringify(doc.suppliers);
profile["suppliers"] =myJSONText;
...
res.render('profile.ejs',{profile:profile});

On front-end I get a plain string with json-data. I parse it via jQuery to an object:

var jsonObject = jQuery.parseJSON('<%= profile.suppliers %>');
for (var i=0; i<jsonObject.length; i++){
    //trying to show field 'name' for every supplier
    alert(jsonObject[i]['lastname']);
}

...and it doesnt work, but should to alert me twice. I've tried to inspect a plain-text JSON-string, comming to front-end, and found out such symbols:

[{&quot;lastname&quot;: &quot; ... 

It seems that jQuery.parseJSON is not able to create a valid object from such string. What I'm doing wrong? Thanks!

UPDATE: Well, I've turned my code into:

NodeJS code:

profile["suppliers"] =doc.suppliers;
res.render('profile.ejs', { profile:profile });

jQuery code:

for (var i=0; i<'<%= profile.suppliers %>'.length; i++){
//trying to show field 'name' for every supplier
alert('<%= profile.suppliers %>'[i]['lastname']);
}

and it gives me never-ending loop of undefined alerts.

UPDATE 2: I've updated my source code, so:

NodeJS:

var myJSONText = JSON.stringify(doc.suppliers);
profile["suppliers"] =myJSONText;
res.render('profile.ejs',{profile:profile});

Client:

var jsonObject = <%- profile.suppliers %>;
$.each(jsonObject, function(item) {
    alert(item.lastname);
});

Generated source code:

var jsonObject = [{"lastname":"lastname1","firstname":"firstname1","middlename":"middlename1","mobtel":"mobtel1","worktel":"worktel1","email":"email1"},{"lastname":"lastname2","firstname":"firstname2","middlename":"middlename2","mobtel":"mobtel2","worktel":"worktel2","email":"email2"}];

Seems to be ok, but still gives me undefined alerts. Hoever, it alerts only twice, that means that it parses JSON correctly and just cannot get access to lastname property?

4
  • Why do you have to stringify your JSON in the first place? EJS should handle the object fine. Commented Jun 11, 2012 at 20:01
  • I've updated original post. Please, take a look. Commented Jun 11, 2012 at 20:15
  • @WesJohnson: It needs to be stringified so that it can be inserted into the javascript file. However, it does not need to be parsed at the other end. Commented Jun 11, 2012 at 20:27
  • This part of your code is broken: i<'<%= profile.suppliers %>'.length. You're iterating over the length of a string, not an array of objects. Commented Jun 11, 2012 at 20:39

2 Answers 2

9

As you correctly diagnosed, &quot;s are being inserted into your JSON. This renders it invalid, preventing it being decoded.

This is because in ejs, <%= ... %> does html output escaping, hence the &quot;. You need to use <%- profile.suppliers %> to avoid this.

There's no need to use JSON.parse on the client: JSON is already valid javascript code, so can be inserted straight into the code, rather than being stored as a string literal.

var jsonObject = <%- profile.suppliers %>;
$.each(jsonObject, function() {
    alert(this.lastname);
});
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, I'll try your solution if Wes' and Terry's variant without stringifying object to plain text will not work
Thanks, I got it, however it doesn't work. If I use your code directly, script doesn't work. If I use quotes (var jsonObject = '<%- profile.suppliers %>';), it still gives me an never-ending loop of undefined alerts.
Let me note, that I dont stringify object on backend-side now
Oh, I've just saw your comment that I must stringify JSON-object.
@IlyaRusanen: Does it work now then? Have a look at the source code it generates if it doesn't.
|
0

As Wes is eluding to, I think you're doing unnecessary stringifying/parsing.

Try this:

var suppliers = // your JSON source

$(suppliers).each(function() {
   alert(this.lastname);
});

3 Comments

I've tried var suppliers = '<%= profile.suppliers %>'; $(suppliers).each(function() { alert(this.lastname); }); but no luck :(
I'm not familiar with ejs, but if Eric's suggestion works I would expect the code I posted to parse it correctly.
Oh, I didn't see Eric's comment about the necessity of stringifying my object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.