我正在用 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/