简体   繁体   English

JSON 中的意外令牌 - position 0

[英]Unexpected token � in JSON at position 0

I have a JS file that makes a GET request to an API which then outputs the results to a JSON file.我有一个 JS 文件,它向 API 发出 GET 请求,然后将结果输出到 JSON 文件。 In another JS file, it is to parse the JSON file by reading it, but is running into errors.在另一个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 code JS代码

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

json file json文件

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

I have removed the square brackets manually, but that didn't seem to fix the issue either.我已经手动删除了方括号,但这似乎也没有解决问题。

Also if I hardcode the json content into the parse() function it seems to work fine in terms of printing the json in proper format.此外,如果我将 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']

Most likely you just need to specify the encoding, so, assuming utf8 :很可能您只需要指定编码,因此,假设utf8

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

or, if you are on an older version of node,或者,如果您使用的是旧版本的节点,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM