user3787706
user3787706

Reputation: 659

Object passed to jade ends up as string

I want to pass an object from node to jade, and use it there in my js. but it ends up as [object Object] string, i don't know why

serverside

var currentProblem = problemMaker.makeProblem(level);
console.dir(currentProblem); // [ { value: 2, operation: '+' }, {value: 1, operation: '-' } ]

res.render('training', {
    // ...
    Oid             : problemOid,
    problemObject   : JSON.stringify(currentProblem)
});

jade

script(type='text/javascript').
    var problemOid = "!{Oid}"  // this WORKS
script(type='text/javascript').
    var problemObj = "!{JSON.parse(problemObject)}"  // this does NOT

(note that webstorm marks "problemObject" as unresolved variable, while Oid seems to be no problem)

browser js

console.log(typeof problemObj);  // string
console.dir(problemObj);         // [object Object],[object Object]

i tried it with and without stringify/parse, no difference. what am i doing wrong?

thanks

Solution

I got it working by remnoving the quotes and removing any JSON.xxxx

working code:

script(type='text/javascript') var problemObj = !{problemObject};

Upvotes: 2

Views: 294

Answers (1)

Alexey B.
Alexey B.

Reputation: 12033

Remove commas and use JSON.stringify insteadof JSON.parse

script var problemObj = !{JSON.stringify(problemObject)}; 

Main idea here

var str = JSON.stringify({a: 1000}); // returns string "{"a":1000}"
console.log(str); // print {"a":1000}

So, in your html you would see

script var str = !{JSON.stringify({a: 1000})}; 

->

<script>
    var str = {"a":1000};
</script>

Upvotes: 3

Related Questions