2017-05-25 199 views
1

我在Node.js中编写我的第一个应用程序。我试图从数据以JSON格式存储的文件中读取一些数据。JSON.parse()会导致错误:`SyntaxError:位置0处JSON中的意外标记'

我得到这个错误:

SyntaxError: Unexpected token  in JSON at position 0

at Object.parse (native)

下面是这部分代码:

//read saved addresses of all users from a JSON file 
fs.readFile('addresses.json', function (err, data) { 
    if (data) { 
     console.log("Read JSON file: " + data); 
     storage = JSON.parse(data); 

这里是console.log输出(我查了以.json文件本身,这是相同的) :

Read JSON file: { 

    "addresses": [] 

} 

在我看来,像一个正确的JSON。为什么JSON.parse()失败呢?

+1

“JSON.parse”参数 – MysterX

+0

@MysterX未启用换行符但语法错误在位置0?和JSON.parse()似乎没有参数来启用换行符。 – K48

+0

你需要设置一个编码,因为BOM –

回答

6

在文件的开头有一个奇怪的字符。

data.charCodeAt(0) === 65279

我会建议:

fs.readFile('addresses.json', function (err, data) { 
if (data) { 
    console.log("Read JSON file: " + data); 
    data = data.trim(); 
    //or data = JSON.parse(JSON.stringify(data.trim())); 
    storage = JSON.parse(data); 
}}); 
+0

你说得对。显然这是一个字节顺序标记。 – K48

+0

我有一个类似的问题,并且在运行'JSON.parse()'之前添加'data.trim()'来修复它。 – Valjas

0

JSON.parse()不允许尾随逗号。所以,你需要摆脱它:

JSON.parse(JSON.stringify(data)); 

你可以找到更多关于它,here

+0

奇怪,我没有在文件中的单个逗号? – K48

+0

这意味着这个:“地址”:[] – Luillyfe

+0

但语法错误是在位置0? – K48

2

尝试这样

fs.readFile('addresses.json','utf-8', function (err, data) { 
    if (data) { 
     console.log("Read JSON file: " + data); 
     storage = JSON.parse(data); 

它,因为需要编码的BOM读取文件之前进行设置。在程序存储库的NodeJS其发出在github上

https://github.com/nodejs/node-v0.x-archive/issues/186

2

这可能是BOM [1。 我已通过保存带有UTF-8 + BOM的内容{"name":"test"}的文件进行了测试,并且它生成了相同的错误。

> JSON.parse(fs.readFileSync("a.json")) 
SyntaxError: Unexpected token in JSON at position 0 

以及基于此建议[2],你可以取代它或删除它,你打电话之前JSON.parse()

例如:

var storage = {}; 

    fs.readFile('a.json', 'utf8', function (err, data) { 
     if (data) { 
      console.log("Read JSON file: " + data); 
      console.log(typeof(data)) 
      storage = JSON.parse(data.trim()); 
     } 
}) 

var storage = {}; 
fs.readFile('a.json', function (err, data) { 
    if (data) { 
     console.log("Read JSON file: " + data); 
     console.log(typeof(data)) 
     storage = JSON.parse(data.toString().trim()); 
    } 
}) 

还可以删除前3个字节(对于UTF-8)通过使用Buffer.slice()

相关问题