Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Rest Api json response and insert data to Jade template (Node.js + express)?

So, i need to parse json response in node.js + express and insert data to jade file. I do this in Sinatra, that was easy, but here.. Response format like:

{
  "status": "200",
  "name": "",
  "port": "7777",
  "playercount": "4",
  "players": "name, of, player"
}
like image 568
Eugen Gorban Avatar asked Dec 11 '25 12:12

Eugen Gorban


1 Answers

Express's res.render() method allows you to pass in local template variables, and use them in your template. For example:

app.route('/', function (req, res) {
  // Your code to get the response, and for example's sake, I'll say it's assigned to 'view_data'.
  if (typeof view_data === 'string') {
    // If you know for sure if your data is going to be an object or a string, 
    // you can leave the if statement out, and instead just parse it (or not if 
    // it's already an object.
    view_data = JSON.parse(view_data);
  }
  res.render('template', view_data);
});

And within template.jade

h1 This is #{name}
pre= status
p #{playercount} players online

The data can be any JSON object, so if you have the response returned as text, you can use JSON.parse() to turn it into a JSON object.

like image 107
Brandon Anzaldi Avatar answered Dec 14 '25 02:12

Brandon Anzaldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!