Search code examples
powershellunicodebyte-order-mark

Modify a JSON file with PowerShell without writing BOM


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?


Solution

  • 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