Javascript Can';t在Node.js中解析JSON
我是一名Node.js初学者,正在尝试读取json文件,但当我在终端中运行“npm start”时,会出现以下错误:Javascript Can';t在Node.js中解析JSON,javascript,json,node.js,parsing,Javascript,Json,Node.js,Parsing,我是一名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.o
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)
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)
当JSON文件中缺少大括号或圆括号时,您得到的错误是正常的
以下是无效的示例_data.json
(末尾缺少一个大括号):
这就产生了错误
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)
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)
如果你有一个有效的json,也许你可以首先尝试/测试。如果你有无效的json,它会给出更好的错误消息。你还应该声明你的变量(jsonObj),并在数据上放一个console.log()来检查。检查是否设置了
error
。\u data.json的内容是什么?正如@Hokutosei所说,尝试使用在线工具检查它以确保其有效性(如果它太复杂,无法用肉眼检查)。顺便说一句,您只需()您的JSON文件即可。谢谢!显然,我的json文件末尾缺少了一些括号。