我有一个 json 对象,它从以下 PowerShell 命令返回:
Get-Service -Name "name" | ConvertTo-Json -Compress > "/to/path/name.json"
如果我基本上在 vscode 中打开文件,它的格式似乎正确。 在我读取文件后
fs.readFile(file, 'utf8', (err, data)...
然后尝试 JSON.parse(data)
我收到错误:
undefined:1
��{
^
SyntaxError: Unexpected token � in JSON at position 0
然后我尝试执行以下操作:
data.replace(/[^\x00-\x7F]/g, "")
仅包含 ASCII 字符,这基本上至少可以与 console.log() 一起使用。
但是 JSON.parse 然后提示:
undefined:1
{
SyntaxError: Unexpected token in JSON at position 1
我不确定那里出了什么问题。希望有人能帮助我。
这是一个示例 json 文件:我认为格式是正确的。只有太多空格被 -compress
PowerShell 参数删除。
{
"CanPauseAndContinue": false,
"CanShutdown": false,
"CanStop": false,
"DisplayName": "OpenSSH Authentication Agent",
"DependentServices": [
],
"MachineName": ".",
"ServiceName": "ssh-agent",
"ServicesDependedOn": [
],
"ServiceHandle": {
"IsInvalid": false,
"IsClosed": false
},
"Status": 1,
"ServiceType": 16,
"StartType": 4,
"Site": null,
"Container": null,
"Name": "ssh-agent",
"RequiredServices": [
]
}
最佳答案
您的 JSON 文件似乎有不同的编码,可能是 utf16le 而不是 utf8。
我复制了您的场景并在这里找到了帮助: Strange unicode characters when reading in file in node.js app
fs.readFile(file, 'utf16le', (err, data)...
关于javascript - JSON.parse() : SyntaxError: Unexpected token � in JSON at position 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68498628/