使用 PowerShell 修改 JSON 文件而不编写 BOM
Modify a JSON file with PowerShell without writing BOM
我需要使用 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 修改现有的 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