[英]Interating through imported json in node.js and express, then displaying with jade
[英]Parsing JSON in node.js and displaying in jade
我試圖解析json並以jade的表格格式顯示響應。 請求幫助解析json並將鍵和值顯示為兩列。
Node.js的
exports.postMQinput = function(req, res) {
req.assert('name', 'Queue name field cannot be blank').notEmpty();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/');
}
var options = {
url: 'URL goes here',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify("my body input comes here")
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.render('Views/Details', {
title: 'QUEUE',
name: 'Welcome',
result: body
});
} else {
console.log(response.statusCode);
req.flash('errors', { msg: 'Error during select. Retrying...' });
}
})
};
我的回答是這樣的。
{
"Response": {
"data": {
"length": 123,
"status": "OPEN"
}
}
}
玉:
extends ../layout
block content
.page-header
h3 MESSAGE QUEUE DETAILS
table
thead
tbody
table.table.table-striped.table-bordered.table-hover.table-condensed
tr
th Value
th Attribute
each key, ind in result
td= "LENGTH"
td= key.length
tr
我想要這樣的桌子
長度123
狀態開放
身體來自哪里? 也許你應該運行JSON.parse
?
res.render('Views/Details', {
title: 'QUEUE',
name: 'Welcome',
result: JSON.parse(body)
});
您正在以錯誤的方式使用迭代來從Jade模板構建HTML,我做了這個示例,向您展示如何使用它,以防您獲得一組值。
extends layout
block content
.page-header
h3 MESSAGE QUEUE DETAILS
table.table.table-striped.table-bordered.table-hover.table-condensed
thead
tr
th Value
th Attribute
tbody
for res in result
for obj in Object.keys(res)
tr
td= res[obj]
td= obj
如果您遇到發送JSON的方式有問題,請查看此示例:
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.get('/', function(req, res){
return http.get({
host: 'localhost',
path: '/json'
}, function(response) {
// Continuously update stream with data
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
// Data reception is done, do whatever with it!
var parsed = JSON.parse(body);
console.log(parsed);
res.render("index", {result: parsed});
});
});
});
app.get('/json', function(req, res){
var data = [ {
"length": 123,
"status": "OPEN"
},{
"length": 145,
"status": "CLOSE"
}
]
res.json(data);
});
app.listen(80);
module.exports = app;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.