【问题标题】:Can't parse a JSON in Node.js [duplicate]无法在 Node.js 中解析 JSON [重复]
【发布时间】: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


【解决方案1】:

您的代码对我来说很好用。您的 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)

当您的 JSON 文件中缺少花括号或括号时,您收到 Unexpected end of input 的错误是正常的。

这是一个无效的sample_data.json(末尾缺少一个花括号):

{
    "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)

【讨论】:

  • 谢谢!显然我的 json 文件末尾缺少一些括号。
猜你喜欢
  • 2018-05-17
  • 1970-01-01
  • 2021-03-31
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 2016-01-27
  • 2018-09-13
相关资源
最近更新 更多