[英]Unexpected token in JSON at position 0
I'm trying to read a.json file with fs and parse to a JavaScript object using JSON.parse() function.我正在尝试使用 fs 读取 a.json 文件并使用 JSON.parse() function 解析为 JavaScript object。
const json = JSON.parse(fs.readFileSync('./db.json', (err) => { if (err) throw err; }))
{
"hello": "world"
}
But I'm getting the following error:但我收到以下错误:
undefined:1 { ^ SyntaxError: Unexpected token in JSON at position 0
undefined:1 { ^ SyntaxError: position 0 处 JSON 中的意外标记
Does anyone know what's wrong?有谁知道怎么了?
readFileSync
returns a Buffer
if you don't tell it what encoding to use to convert the file contents to text.如果您不告诉它使用什么编码将文件内容转换为文本,
readFileSync
将返回一个Buffer
。 If you pass a Buffer
into JSON.parse
, it'll get converted to string before being parsed.如果将
Buffer
传递给JSON.parse
,它将在解析之前转换为字符串。 Buffer
's toString
defaults to UTF-8. Buffer
的toString
默认为 UTF-8。
So there are a couple of possible issues:所以有几个可能的问题:
Separately from that, readFileSync
doesn't accept a callback (it returns its result or throw an error instead, because it's synchronous — that's what the Sync
suffix means in the Node.js API).除此之外,
readFileSync
不接受回调(它返回结果或抛出错误,因为它是同步的——这就是Sync
后缀在 Node.js API 中的含义)。 (If it did have a callback, doing throw err
in that callback would be pointless. it wouldn't, for instance, throw an error from the function where you're calling readFileSync
.) (如果它确实有回调,那么在该回调中执行
throw err
将毫无意义。例如,它不会从您调用readFileSync
的 function 中抛出错误。)
If the file isn't UTF-8, tell readFileSync
what encoding to use (I suggest always doing that rather than relying on implicit conversion to string later).如果文件不是 UTF-8,请告诉
readFileSync
使用什么编码(我建议始终这样做,而不是稍后依赖隐式转换为字符串)。 If it's in (say) UTF-16LE ("UTF-16 little endian"), then you'd do this:如果它在(比如说)UTF-16LE(“UTF-16 little endian”)中,那么你会这样做:
const data = JSON.parse(fs.readFileSync('./db.json', "utf16le"));
If it's in UTF-8 with a BOM: Buffer
doesn't remove the BOM when it converts to string, so you end up with what looks like a weird character at position 0 which JSON.parse
doesn't like.如果它在带有 BOM 的 UTF-8 中:
Buffer
在转换为字符串时不会删除 BOM,因此您最终会在 position 0 处看到一个奇怪的字符,而JSON.parse
不喜欢。 If that's the case, you can do this:如果是这种情况,您可以这样做:
const UTF8_BOM = "\u{FEFF}";
let json = fs.readFileSync('./db.json', "utf8");
if (json.startsWith(UTF8_BOM)) {
// Remove the BOM
json = json.substring(UTF8_BOM.length);
}
// Parse the JSON
const data = JSON.parse(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.