无法解析Node.js中的JSON [重复]

时间:2022-09-23 14:00:07

This question is an exact duplicate of:

这个问题与以下内容完全相同:

I am a Node.js beginner and I am trying to read a json file, but when I'm running 'npm start' in the terminal I get this error:

我是一个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)

this is index.js:

这是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;

1 个解决方案

#1


2  

Your code works fine for me. Your JSON file must be erroneous in some way.

你的代码对我来说很好。您的JSON文件必须以某种方式出错。

Here this an example using your code:

这是一个使用您的代码的示例:

invalid JSON:

{
    "test_data": 2
    bla
}

gives the error

给出错误

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)

The error you get Unexpected end of input is normal when missing curly braces or parentheses in your JSON file.

当您在JSON文件中缺少大括号或括号时,您收到的错误意外结束输入是正常的。

Here is an invalid sample_data.json (missing a curly brace at the end):

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

{
    "test_data": 2

which gives the error

这给出了错误

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)

#1


2  

Your code works fine for me. Your JSON file must be erroneous in some way.

你的代码对我来说很好。您的JSON文件必须以某种方式出错。

Here this an example using your code:

这是一个使用您的代码的示例:

invalid JSON:

{
    "test_data": 2
    bla
}

gives the error

给出错误

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)

The error you get Unexpected end of input is normal when missing curly braces or parentheses in your JSON file.

当您在JSON文件中缺少大括号或括号时,您收到的错误意外结束输入是正常的。

Here is an invalid sample_data.json (missing a curly brace at the end):

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

{
    "test_data": 2

which gives the error

这给出了错误

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)