【问题标题】:Can't parse json with node.js无法使用 node.js 解析 json
【发布时间】:2023-03-10 04:40:01
【问题描述】:

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

有什么帮助吗? 谢谢!

【问题讨论】:

  • 您确定文件存在于该路径并且文件中有内容?
  • 是的。我已经检查了文件
  • 顺便说一句,你可以简单的require json 文件。
  • Can't parse a JSON in Node.js 的可能重复项

标签: html json parsing web


【解决方案1】:

readFile 是异步版本。您应该只使用 readFileSync,或者将其重写为适当的异步。

console.log('analoc request');

var fs = require('fs');

 fs.readFile('./files/sample_data.json', function(err,config){
console.log('Config: ' + JSON.parse(config));
});

或者:

var config = fs.readFileSync('./files/sample_data.json');
console.log('Config: ' + JSON.parse(config));

【讨论】:

    【解决方案2】:

    readFile doesn't have a return value。您正在尝试解析 "undefined",就好像它是 JSON 一样。文件被读取后传递给回调函数。

    fs.readFile('./files/sample_data.json', function (err, data) {
        if (err) throw err;
        var config = JSON.parse(data);
        console.log('Config: ', config);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-28
      • 2018-12-02
      • 1970-01-01
      • 2015-05-16
      • 2017-04-06
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多