我需要使用 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?
最佳答案
这与 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
关于powershell - 在不编写 BOM 的情况下使用 PowerShell 修改 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936043/