无法parsingNode.js中的JSON

我是一个Node.js初学者,我正在尝试阅读一个json文件,但是当我在terminal中运行“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文件在某种程度上必须是错误的。

这里使用你的代码这个例子:

无效的JSON:

 { "test_data": 2 bla } 

给出错误

 Example app listening at http://:::3000 undefined:3 bla ^ SyntaxError: Unexpected token b at Object.parse (native) at /tmp/node_help/index.js:15:32 at fs.js:334:14 at FSReqWrap.oncomplete (fs.js:95:15) 

错误你得到Unexpected end of input是正常的,当你的JSON文件中缺less花括号或括号。

这是一个无效的sample_data.json (最后缺less一个大括号):

 { "test_data": 2 

这给出了错误

 SyntaxError: Unexpected end of input at Object.parse (native) at /tmp/node_help/index.js:15:32 at fs.js:334:14 at FSReqWrap.oncomplete (fs.js:95:15)