Wednesday, November 29, 2017

How to use JSON.parse in nunjucks

Leave a Comment

i am get data in mongodb and express return occurs without errors but I wanted to use JSON.parse in the final results of my .find see below how I'm trying to do this

  app.get("/login", (req, res) => {     var credentialClient = {       expire_at: false,       __v: false,       _id: false     };      rememberMe.find({ username: "test-login" }, credentialClient, function (err, credentialInfo) {       if (err) {         res.send(err);       } else {         res.render("login.html", {           usernameClient: JSON.parse(credentialInfo)         });       }     });   }); 

Without JSON.parse the final rendering stays that way in my login.html

{ username: 'test-login' } 

The final results appear in login.html

<p class="center-align black-text" id="preFinalCredentialClient">{{ usernameClient }}</p> 

Thanks for helping me!

3 Answers

Answers 1

I hope below code will work for you. In below example, I have kept static json data. In your case you can store json data in any variable and render

index.nunjucks passing that variable.

var express = require( 'express' ) ;  var nunjucks = require( 'nunjucks' ) ;  var app = express() ;  app.get( '/', function( req, res )   {  var jsondata =   {  firstName: "Rakesh", lastName: "Barani"  };  return res.render('index.njk', {data:jsondata}) ;  res.render('index.njk', {data: jsondata}) }); 

Answers 2

credentialInfo is already JS object, no need to parse it.

app.get("/login", (req, res) => {     var credentialClient = {       expire_at: false,       __v: false,       _id: false     };      rememberMe.find({ username: "test-login" },          credentialClient, function (err, credentialInfo) {       if (err) {         res.send(err);       } else {         res.render("login.html", {           usernameClient: credentialInfo         });       }     });   });  <p class="center-align black-text" id="preFinalCredentialClient">{{ usernameClient.username }}</p> 

On the client, you can then access the properties of usernameClient.

Answers 3

It already returns JSON response so You can use this:

res.render("login.html", {    usernameClient: credentialInfo.username }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment