javascript - JSON.parse() 导致错误 : `SyntaxError: Unexpected token in JSON at position 0`

标签 javascript json node.js

我正在用 Node.js 编写我的第一个应用程序。我正在尝试从数据以 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() 会失败?

最佳答案

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

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);
 }});

关于javascript - JSON.parse() 导致错误 : `SyntaxError: Unexpected token in JSON at position 0` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44176194/

相关文章:

node.js - remoteDisconnect socket.io 和 redis

javascript - 生成子进程转义引号

javascript - 导入/需要 JSON 文件作为克隆到 Vue 数据属性中

php - 将 SQL 数据解析为 JSON 以允许用户登录网站时是否存在性能/安全问题或优势?如果有,它们是什么?

json - 无法将外部结构直接调用到 map[string]struct

node.js - 使用 Upstart 运行 node.js 服务器导致 'terminated with status 127' 上的 'ubuntu 10.04'

javascript - openshift/nodeJS 中的 Websocket 失败

javascript - 如何将矩阵转换为一行的数组

javascript - 从外部函数中过滤 Fullcalendar 4

javascript - JS : Serializing an object with methods (or an instance) to json/string without losing the methods