【发布时间】:2015-06-28 07:40:35
【问题描述】:
我是一个 Node.js 初学者,我正在尝试读取一个 json 文件,但是当我在终端中运行“npm start”时,我收到了这个错误:
undefined:3462
SyntaxError: Unexpected end of input
at Object.parse (native)
at /Users/alonbond/node_apps/analoc_2/analoc/routes/index.js:15:20
at fs.js:334:14
at FSReqWrap.oncomplete (fs.js:95:15)
这是 index.js:
var express = require('express');
var fs = require('fs');
var app = express.Router();
/* GET home page. */
app.get('/', function(req, res, next) {
console.log('Welcome to Express.js');
res.render('index', { title: 'Express' });
});
/* GET json */
app.get('/analoc/', function(req, res) {
fs.readFile('./sample_data.json', function(error, data){
jsonObj = JSON.parse(data);
res.send('THE DATA: ', jsonObj);
});
});
module.exports = app;
【问题讨论】:
-
也许你可以尝试/测试如果你有一个有效的 json 先在这里jsonlint.com 如果你有无效的 json,它会给出更好的错误消息
-
你还应该声明你的变量(jsonObj),并在要检查的数据上放置一个console.log()。
-
检查是否设置了
error... -
sample_data.json 的内容是什么?正如@Hokutosei 所说,尝试使用在线工具检查它以确保它是有效的(如果它太复杂而无法用肉眼检查)。
-
顺便说一句,你可以简单地 require() 你的 JSON 文件。
标签: javascript json node.js parsing