Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell convert string to json

In PowerShell I have the following string that I read from file and need to convert to json:

"@{Account='User01';Domain='Domain01';Admin='True'}"

In my PS script I try to do this (simplified):

$myStr = "@{Account='User01';Domain='Domain01';Admin='True'}" | ConvertTo-Json
$mystr

the result of myStr is:

"@{Account=\u0027User01\u0027;Domain=\u0027Domain01\u0027;Admin=\u0027True\u0027}"

and not a json I can use. note that the @ sign at the beginning of the string is what I get from the file.

How can I convert it to an object I can use?

like image 584
developer82 Avatar asked Jan 08 '23 08:01

developer82


1 Answers

You could try some string manipulation to get it in an expected JSON format, and then use ConvertFrom-Json to convert it to a PSCustomObject.

Simple Example: (simple because this assumes that these characters being replaced will only be delimiters)

# First, clean up the string.
PS C:\> $mystring = "@{Account='User01';Domain='Domain01';Admin='True'}"
PS C:\> $mystring = $mystring -replace "^@", ""
PS C:\> $mystring = $mystring -replace "=", ":"
PS C:\> $mystring = $mystring -replace ";", ","
PS C:\> $mystring
{Account:'User01',Domain:'Domain01',Admin:'True'}

# Afterwards, convert to PSCustomObject.
PS C:\> $myobject = $mystring | ConvertFrom-Json
PS C:\> $myobject

Account                                 Domain                                  Admin
-------                                 ------                                  -----
User01                                  Domain01                                True

This can also be converted back to JSON:

PS C:\> $myobject | ConvertTo-Json
{
    "Account":  "User01",
    "Domain":  "Domain01",
    "Admin":  "True"
}
like image 155
Anthony Neace Avatar answered Jan 13 '23 14:01

Anthony Neace