SyntaxError:意外令牌{在JSON中的位置0

时间:2019-05-23 19:54:39

标签: node.js json

我正在尝试解析JSON文件,但在位置0处得到了预期的令牌{

SolaceConnetionParser.js

class SolaceConnectionParser {
    constructor() { }

    //TODO: cannot parse json correctly
    parse(filepath) {
        const connectionArgs = [];
        console.log('File path: ' + filepath);
        const rawData = fs.readFileSync(filepath, 'utf-8').toString;
        const contents = JSON.parse(rawData);
        return contents;
    }
}

module.exports = SolaceConnectionParser;

const path = require('path');
const fs = require('fs');

const parser = new SolaceConnectionParser();
const filepath = path.join(__dirname + '../../../configs/test.json');
console.log(parser.parse(filepath));

test.json

{
  "key": "value"
}

预期: 代码中的其余语句应输出到控制台(即JSON内容)。
实际:

$ node SolaceConnectionParser.js
File path: C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\configs\test.json
undefined:1
{
^

SyntaxError: Unexpected token  in JSON at position 0
    at JSON.parse (<anonymous>)
    at SolaceConnectionParser.parse (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:9:31)
    at Object.<anonymous> (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:26:31)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)

2 个答案:

答案 0 :(得分:0)

JSON对象表示为String,而fs.readFileSync()返回Buffer

更改

const rawData = fs.readFileSync(filepath, 'utf-8');

const rawData = fs.readFileSync(filepath, 'utf-8').toString();

你应该很好。

答案 1 :(得分:0)

应用Rob Raisch的答案并修剪字符串后,问题得到解决。

const rawData = fs.readFileSync(filepath, 'utf-8').toString().trim();