【问题标题】:Modify a JSON file with PowerShell without writing BOM使用 PowerShell 修改 JSON 文件,无需编写 BOM
【发布时间】:2016-02-29 09:30:27
【问题描述】:
我需要使用 PowerShell 修改现有的 UTF8 编码 JSON 文件。我尝试使用以下代码:
$fileContent = ConvertFrom-Json "$(Get-Content $filePath -Encoding UTF8)"
$fileContent.someProperty = "someValue"
$fileContent | ConvertTo-Json -Depth 999 | Out-File $filePath
这会将 BOM 添加到文件中,并将其编码为 UTF16。是否可以让ConvertFrom-Json 和ConvertTo-Json 不进行编码/BOM?
【问题讨论】:
标签:
powershell
unicode
byte-order-mark
【解决方案1】:
这与ConvertTo-Json 或ConvertFrom-Json 无关。编码由输出 cmdlet 定义。 Out-File 默认为 Unicode,Set-Content 为 ASCII。对于它们中的每一个,都可以明确定义所需的编码:
... | Out-File $filePath -Encoding UTF8
或
... | Set-Content $filePath -Encoding UTF8
这仍然会将 (UTF8) BOM 写入输出文件,但无论如何我都不会认为没有 BOM 的 UTF-8 编码是一种好习惯。
如果您想要 ASCII 编码的输出文件(无 BOM),请将 UTF8 替换为 Ascii:
... | Out-File $filePath -Encoding Ascii
或
... | Set-Content $filePath # Ascii is default encoding for Set-Content
【讨论】:
-
谢谢!关键是JSON spec需要Unicode编码但不支持BOM
-
谢谢!我的问题是fetch 在获取和解析使用Out-File 编写的文件时抱怨位置0(BOM)出现意外字符。设置-Encoding Ascii解决了我的问题。