PowerShell: ConvertTo-Json problem containing special characters PowerShell: ConvertTo-Json problem containing special characters powershell powershell

PowerShell: ConvertTo-Json problem containing special characters


Try the Unescape() method:

$jsonfile | ConvertTo-Json | % { [System.Text.RegularExpressions.Regex]::Unescape($_) } | Out-File "new.json"


This is caused by the automatic character escape feature of Convertto-Json and it affects several symbols such as <>\'&

ConvertFrom-Json will read the escaped characters properly. Using your example:

PS C:\> {"Password\u0026123"} | ConvertFrom-JsonPassword&123

And your example code results in a file that has escaped characters, but ConvertFrom-Json can read it back to the original passwords. See below:

PS C:\> (Get-Content .\example.json -Encoding Ascii) -join "`n" | ConvertFrom-JsonServer1                                  Server2-------                                  -------@{username=root; password=Password&dfdf} @{username=admin; password=Password&1234}PS C:\> (Get-Content .\new.json -Encoding Ascii) -join "`n" | ConvertFrom-JsonServer1                                  Server2-------                                  -------@{username=root; password=Password&dfdf} @{username=admin; password=Password&1234}

If you need the passwords to be stored unescaped, some fancier work may be needed. See this thread about Converting Unicode strings to escaped ascii strings

Alternatively, avoid affected characters if possible.