用PowerShell修改一个JSON文件,不用写BOM [英] Modify a JSON file with PowerShell without writing BOM

查看:50
本文介绍了用PowerShell修改一个JSON文件,不用写BOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 PowerShell 修改现有的 UTF8 编码 JSON 文件.我尝试使用以下代码:

I need to modify an existing UTF8 encoded JSON file with PowerShell. I tried with the following code:

$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?

This adds a BOM to the file and also encodes it in UTF16. Is it possible to have ConvertFrom-Json and ConvertTo-Json do not do the encoding / BOM?

推荐答案

这与 ConvertTo-JsonConvertFrom-Json 无关.编码由输出 cmdlet 定义.Out-File 默认为 Unicode,Set-Content 为 ASCII.对于它们中的每一个,都可以明确定义所需的编码:

This has nothing to do with ConvertTo-Json or ConvertFrom-Json. The encoding is defined by the output cmdlet. Out-File defaults to Unicode, Set-Content to ASCII. With each of them the desired encoding can be defined explicitly:

... | Out-File $filePath -Encoding UTF8

... | Set-Content $filePath -Encoding UTF8

这仍会将 (UTF8) BOM 写入输出文件,但无论如何我都不会认为没有 BOM 的 UTF-8 编码是一个好习惯.

That will still write a (UTF8) BOM to the output file, but I wouldn't consider UTF-8 encoding without BOM a good practice anyway.

如果您想要 ASCII 编码的输出文件(无 BOM),请将 UTF8 替换为 Ascii:

If you want ASCII-encoded output files (no BOM) replace UTF8 with Ascii:

... | Out-File $filePath -Encoding Ascii

... | Set-Content $filePath     # Ascii is default encoding for Set-Content

这篇关于用PowerShell修改一个JSON文件,不用写BOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆