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?
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With