Question:
In PowerShell I have the following string that I read from file and need to convert to json:
1 2 |
"@{Account='User01';Domain='Domain01';Admin='True'}" |
In my PS script I try to do this (simplified):
1 2 3 |
$myStr = "@{Account='User01';Domain='Domain01';Admin='True'}" | ConvertTo-Json $mystr |
the result of myStr
is:
1 2 |
"@{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?
Answer:
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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# 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:
1 2 3 4 5 6 7 |
PS C:\> $myobject | ConvertTo-Json { "Account": "User01", "Domain": "Domain01", "Admin": "True" } |