Json 无法读取属性';长度';未定义node.js的名称
我将一些JSON传递到Node.js中,并尝试解析它并将其显示在页面上。但是,在对堆栈溢出进行搜索并尝试各种解决方案(当前正在阅读)后,我收到了以下错误:Json 无法读取属性';长度';未定义node.js的名称,json,node.js,pug,Json,Node.js,Pug,我将一些JSON传递到Node.js中,并尝试解析它并将其显示在页面上。但是,在对堆栈溢出进行搜索并尝试各种解决方案(当前正在阅读)后,我收到了以下错误: TypeError: D:\Programming\node\yale\views\index.jade:10 8| //- p= post.comments[1].data 9| each comment in post.comments > 10|
TypeError: D:\Programming\node\yale\views\index.jade:10
8| //- p= post.comments[1].data
9| each comment in post.comments
> 10| each text in comment.data
11| p= text.from.name
12|
13|
Cannot read property 'length' of undefined
at $$l (eval at <anonymous> (D:\Programming\node\yale\node_modules\jade\lib\jade.js:172:8), <anonymous>:122:31)
at $$l (eval at <anonymous> (D:\Programming\node\yale\node_modules\jade\lib\jade.js:172:8), <anonymous>:153:4)
at eval (eval at <anonymous> (D:\Programming\node\yale\node_modules\jade\lib\jade.js:172:8), <anonymous>:160:4)
at eval (eval at <anonymous> (D:\Programming\node\yale\node_modules\jade\lib\jade.js:172:8), <anonymous>:301:4)
at eval (eval at <anonymous> (D:\Programming\node\yale\node_modules\jade\lib\jade.js:172:8), <anonymous>:311:21)
at res (D:\Programming\node\yale\node_modules\jade\lib\jade.js:173:38)
at Object.exports.render (D:\Programming\node\yale\node_modules\jade\lib\jade.js:269:10)
at Object.exports.renderFile (D:\Programming\node\yale\node_modules\jade\lib\jade.js:305:18)
at View.exports.renderFile [as engine] (D:\Programming\node\yale\node_modules\jade\lib\jade.js:290:21)
at View.render (D:\Programming\node\yale\node_modules\express\lib\view.js:76:8)
翡翠索引
扩展布局
block content
each post in datas
div(id='post')
p= post.from.name
p= post.message
//- p= post.comments[1].data
each comment in post.comments
each text in comment.data
p= text.from.name
Index.js
var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var file = '../public/sample.json';
var filePath = path.join(__dirname, '../public/sample.json');
/* GET home page. */
router.get('/', function(req, res) {
fs.readFile(filePath, 'utf8', function(err, data) {
if(err) {
console.log(err);
} else {
data = JSON.parse(data);
res.render('index', { datas: data });
console.log(data);
}
});
});
module.exports = router;
我的问题是,如何检索
Comments
对象中的数据?谢谢你的帮助 comments
不是JSON结构中的数组,而是一个对象。尝试将其设置为数组。我认为您希望迭代posts数据,而不是对象本身
each comment in post.comments.data
p= comment.from.name
我该怎么做呢?
each comment in post.comments.data
p= comment.from.name