无法解析Node.js中的JSON [英] Can't parse a JSON in Node.js

查看:204
本文介绍了无法解析Node.js中的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js初学者,正在尝试读取json文件,但是当我在终端中运行"npm start"时,出现此错误:

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:

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:

this is 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文件在某种程度上必须是错误的.

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

以下是使用您的代码的示例:

Here this an example using your code:

无效的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是正常的.

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

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

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

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

这篇关于无法解析Node.js中的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆