3

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"
}
Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55
  • var obj = `JSON.parse(json_str)`? – Josh C. Sep 30 '15 at 22:53
  • 1
    Hello and welcome to StackOverflow! I recommend you should have a search in the site for similar questions. Parsing JSON is a question that has been asked and answered many times [for example](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object). I also found [this question](http://stackoverflow.com/questions/32021147/output-a-server-generated-json-object-in-jade-without-json-parse) which seemed to be very similar to yours. – 1800 INFORMATION Sep 30 '15 at 23:11

1 Answers1

1

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.

Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55