I have a node/express application and want to pass a javascript object to the browser. Currently I do this by JSON.stringify
ing the object and printing it into the html:
Node.js/express:
var myObject = /* loaded from db, might look like this: */
{something: "that has 's and \"s"},
myObjectString = JSON.stringify(myObject);
...
res.render('my-template', {..., myObjectString: myObjectString});
my-template.handlebars
:
<html>
...
<script type="text/javascript">
var myObjectInBrowser = JSON.parse('{{{myObjectString}}}');
/* do something to the DOM based on myObjectInBrowser */
</script>
</html>
This leads to problems if myObject
contains strings that contain '
or "
. This answer to a similar question suggests that I could use replace
to manually adjust the stringified object to get everything quoted correctly.
Is there a simpler way to pass a javascript object from node.js to the browser (without doing another request)?