powershell - 在不编写 BOM 的情况下使用 PowerShell 修改 JSON 文件

标签 powershell unicode byte-order-mark

我需要使用 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-JsonConvertTo-Json 不进行编码/BOM?

最佳答案

这与 ConvertTo-JsonConvertFrom-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/

相关文章:

powershell - 如何使用powershell读取CSV文件的第一列

powershell - powershell中带引号的字符串变量

azure - 如何在powershell中循环遍历2个数组?

PHP:如何创建编码为 "UTF-8 without BOM"的文件

c# - 从 C# 以 32 位或 64 位运行 PowerShell

dictionary - 免费提供中文、日文、中日韩字符字典数据

r - 在包函数中使用非ASCII字符

iPhone - 将 NSString 编码从 WindowsCP1251 转换为 UTF8

php - BOM 错误,未检测到输入错误

node.js - 使用 Node/Express 解析 CSV 文件会输出奇怪的\x001 代码