题 如何在jade中渲染json对象并循环遍历结果


当我将一个JSON字符串发送到jade文件进行rending时,我只能打印出整个字符串,而不是它的元素。如何打印出特定元素或循环访问JSON字符串?

app.js:

var http    = require('http'), 
    express = require('express'),
    net     = require('net');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
    var json_string = {"action":"date +%s","result":"1367263074"};
    res.render('index', { layout : 'layout', json: JSON.stringify(json_string) });
})
app.listen(3000);

layout.jade:

!!!5
html
 head
  body
   p !{json}
   p !{json.result}
   p ---
    each val, key in json
     p #{key}: #{val}

预期产量:

{"action":"date +%s","result":"1367263074"}
1367263074
---
action: date +%s
result: 1367263074

实际产量:

{"action":"date +%s","result":"1367263074"}

---
0: {
1: "
2: a
3: c
4: t
5: i
6: o
7: n
8: "
9: :
10: "
11: d
12: a
13: t
14: e
15:
16: +
17: %
18: s
19: "
20: ,
21: "
22: r
23: e
24: s
25: u
26: l
27: t
28: "
29: :
30: "
31: 1
32: 3
33: 6
34: 7
35: 2
36: 6
37: 3
38: 0
39: 7
40: 4
41: "
42: }

14
2018-04-30 13:35


起源




答案:


你为什么要传递一个字符串?尝试这个:

var ob = { action:"date +%s", result:"1367263074"};
res.render('index', { layout : 'layout', json: ob });

或者这样做:

-var ob = JSON.parse(json)
-for(var prop in ob)
 p #{prop}: #{ob[prop]}

16
2018-04-30 13:40





在这一行: each val, key in json 您首先将JS对象字符串化(服务器端),不要将其字符串化以将其作为对象。

所以这一行:

res.render('index', { layout : 'layout', json: JSON.stringify(json_string) });

res.render('index', { layout : 'layout', json: json_string });

7
2018-04-30 13:41





如果您正在寻找循环一系列操作和结果,那么请使用Mathieu Amiot的建议加上以下代码:

each key in json   
    p !{key.action} !{key.result}

2
2017-07-05 16:45