簡體   English   中英

JSON 中的意外令牌 - position 0

[英]Unexpected token � in JSON at position 0

我有一個 JS 文件,它向 API 發出 GET 請求,然后將結果輸出到 JSON 文件。 在另一個JS文件中,它是通過讀取JSON文件來解析它,但是遇到了錯誤。

SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse (<anonymous>) at C:\Users\user\Desktop\node_express\oncall_api\readjson.js:5:24

JS代碼

const fs = require('fs');
fs.readFile('log.json', (err, data) => {
    if (err) throw err;
    let results = JSON.parse(data);
    console.log(results);
});

json文件

{"personName":["personOne"],"alsoNotifyList":null,"currStart":"2021-03-30T09:00:00-07:00","currEnd":"2021-04-06T09:00:00-07:00"}

我已經手動刪除了方括號,但這似乎也沒有解決問題。

此外,如果我將 json 內容硬編碼到 parse() function 中,則在以正確格式打印 json 方面似乎工作正常。

let results = JSON.parse('{"personName":["personOne"],"alsoNotifyList":null,"currStart":"2021-03-30T09:00:00-07:00","currEnd":"2021-04-06T09:00:00-07:00"}');
console.log(results.personName) //works and return ['personOne']

很可能您只需要指定編碼,因此,假設utf8

fs.readFile('log.json', { encoding: 'utf8' }, (err, data) => {

或者,如果您使用的是舊版本的節點,

fs.readFile('log.json', 'utf8', (err, data) => {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM