Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

javascript - how to render json object in jade and loop through results

When I send a JSON string to a jade file for rending I'm only able to print out the string in it's entirety but not by it's elements. How do I print out specific elements or loop through the JSON string?

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}

expected output:

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

actual output:

{"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: }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why are you passing a string? Try this:

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

Or do this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...