Modify a JSON file with PowerShell without writing BOM

泄露秘密 提交于 2019-12-20 02:42:23

问题


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

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?


回答1:


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

or

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

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.

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

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

or

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


来源:https://stackoverflow.com/questions/33936043/modify-a-json-file-with-powershell-without-writing-bom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!