'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?
Solution 1:[1]
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"
}
Solution 2:[2]
The above holds for a Json or PS object with depth of at most 2. If your object contains nested objects, you need to specify the -Depth parameter.
PS C:\> $json=
'{
"level1":[
{
"attr1":"value1",
"level2":[
{
"attr2.1":"value2.1",
"attr2.2":"value2.2"
}
]
}
],
"Comment":"3-level object"
}'
PS C:\> $psobj = ConvertFrom-Json $json
PS C:\> $psobj
level1 Comment
------ -------
{@{attr1=value1; level2=System.Object[]}} 3-level object
PS C:\> Convertto-Json $psobj
{
"level1": [
{
"attr1": "value1",
"level2": ""
}
],
"Comment": "3-level object"
}
PS C:\> Convertto-Json $psobj -Depth 3
{
"level1": [
{
"attr1": "value1",
"level2": [
"@{attr2.1=value2.1; attr2.2=value2.2}"
]
}
],
"Comment": "3-level object"
}
PS C:\> Convertto-Json $psobj -Depth 4
{
"level1": [
{
"attr1": "value1",
"level2": [
{
"attr2.1": "value2.1",
"attr2.2": "value2.2"
}
]
}
],
"Comment": "3-level object"
}
As you might guess, the default value for Depth is 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
