JSON.parse()导致错误:`SyntaxError:位于0的JSON中的意外标记

7 javascript json node.js

我正在Node.js中编写我的第一个应用程序.我试图从一个文件中读取一些数据,其中数据以JSON格式存储.

我收到此错误:

SyntaxError:位于0的JSON中的意外标记

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);
Run Code Online (Sandbox Code Playgroud)

这是console.log输出(我检查了.json文件本身,它是一样的):

Read JSON file: ?{

    "addresses": []

}
Run Code Online (Sandbox Code Playgroud)

在我看来,这似乎是一个正确的JSON.为什么JSON.parse()失败呢?

blu*_*ipy 15

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

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);
 }});
Run Code Online (Sandbox Code Playgroud)


Lui*_*yfe 5

JSON.parse()不允许尾随逗号。因此,您需要摆脱它:

JSON.parse(JSON.stringify(data));
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到更多有关它的信息。


Ari*_* Ax 5

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

> JSON.parse(fs.readFileSync("a.json"))
SyntaxError: Unexpected token  in JSON at position 0
Run Code Online (Sandbox Code Playgroud)

根据此处 [ 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());
    }
});
Run Code Online (Sandbox Code Playgroud)

或者

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());
    }
})
Run Code Online (Sandbox Code Playgroud)

您还可以使用Buffer.slice().