2015-09-30 50 views
3

所以,我需要解析node.js + express中的json響應,並將數據插入到jade文件中。我這樣做是西納特拉,這很簡單,但在這裏.. 響應格式,如:如何解析Rest Api json響應並將數據插入Jade模板(Node.js + express)?

{ 
    "status": "200", 
    "name": "", 
    "port": "7777", 
    "playercount": "4", 
    "players": "name, of, player" 
} 
+0

var obj ='JSON.parse(json_str)'? –

+1

你好,歡迎來到StackOverflow!我建議你應該在網站上搜索類似的問題。解析JSON是一個已經被問及多次回答的問題[例如](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object)。我也發現[這個問題](http://stackoverflow.com/questions/32021147/output-a-server-generated-json-object-in-jade-without-json-parse)這似乎是非常類似於你的。 –

回答

1

快遞的res.render()方法可以讓你在本地模板傳遞變量,且模板中使用它們。例如:

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); 
}); 

並在template.jade

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

的數據可以是任何JSON對象,所以如果你有響應返回文本,你可以使用JSON.parse()把它變成一個JSON對象。

+0

非常感謝! –