【发布时间】:2021-09-30 13:10:11
【问题描述】:
我有一个从以下 PowerShell 命令返回的 json 对象:
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": [
]
}
【问题讨论】:
-
您的 name.json 文件没有正确的语法。能发一下name.json的内容吗?
-
这可能是 PowerShell 命令倾向于添加的 UTF-16 BOM。
-
@ÁlvaroGonzález 我该如何解决这个问题?只需将文件读取为 utf-16?
标签: javascript json powershell jsonparser