2

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 Answer 1

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! The point is that the JSON spec requires Unicode encoding but doesn't support BOM
Thanks! My problem was fetch complained about an unexpected character at position 0 (BOM) when fetching and parsing a file, written using Out-File. Setting -Encoding Asciisolved my problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.