Raj
Raj

Reputation: 343

How to escape special characters in PowerShell while creating json object

I have powershell script that I run in an installer while installation. I tried alot of examples to escape special characters, meaning if user choose username or password and that contains characters like slashes or commas, powershell fails to create json objects. Sometimes if user enters a comma, instead of taking it as a string, it breaks into json array. Following are my example and values for varibles are coming from installer, which are valid strings. Thank you for your insights.

$pathToJson = $InstalledPath+"appsettings.json"
$a = Get-Content $pathToJson | ConvertFrom-Json
$a.SQLConnectionSettings.SqlServerIp=$GkDbIP
$a.SQLConnectionSettings.SqlInitialCatalog=$GkDbName
$a.SQLConnectionSettings.SqlIntegratedSecurity=$SqlAuthType
$a.SQLConnectionSettings.SqlUserId=$GkDbUsername
$a.SQLConnectionSettings.SqlPassword=$SQLPassword
$a | ConvertTo-Json | set-content $pathToJson   

Upvotes: 2

Views: 6387

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125332

You can use Regex.Unescape to unscape the json content. For example:

$OBJECT = @{username="someone"; password="someone's \password"}
$OBJECT | ConvertTo-Json -depth 100 |
     % { [System.Text.RegularExpressions.Regex]::Unescape($_) } |
         Out-File "D:\somefile.json" -Encoding utf8

And here is the result:

{
    "password":  "someone's \password",
    "username":  "someone"
}

If you don't use unescape, the password will be saved as "someone\u0027s \\password".

Upvotes: 4

Related Questions