简体   繁体   中英

Powershell convertfrom -Json error after converting to base64

I am trying to do the below in powershell and getting an error unable to figure out reason.

Below works fine

$config = @"
{
    "Common.BinDir": "G:\result",
    "Infrastructure.WebRoot": "G:\result20171120"
}
"@

$abc = ConvertFrom-Json $testconfig

But when I pass in base64 of the above(as script which I use expects base64)

$config = "QCINCnsNCgkiQ29tbW9uLkJpbkRpciI6ICJHOlxyZXN1bHQiLA0KCSJJbmZyYXN0cnVjdHVyZS5XZWJSb290IjogIkc6XHJlc3VsdDIwMTcxMTIwIg0KfQ0KIkA="
$decodedConfig = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($config))
$abc = ConvertFrom-Json $decodedConfig

I get below error upon running the convert command

ConvertFrom-Json : Invalid JSON primitive: .
At line:1 char:8
+ $abc = ConvertFrom-Json $decodedConfig
+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], 
ArgumentException
    + FullyQualifiedErrorId : 
System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

The following code snippet should work as expected for the given $config :

$config = "QCINCnsNCgkiQ29tbW9uLkJpbkRpciI6ICJHOlxyZXN1bHQiLA0KCSJJbmZyYXN0cnVjdHVyZS5XZWJSb290IjogIkc6XHJlc3VsdDIwMTcxMTIwIg0KfQ0KIkA="
$decodedConfig = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($config))
$abc = ConvertFrom-Json -InputObject $(
    Invoke-Expression -Command $decodedConfig.Replace('\', '\\')
    )

I believe there are two things
1) String decoded from base64 contains @" and "@ - as part of string, not qualifier - so

$decodedString is:

@"
{
    "Common.BinDir": "G:\result",
    "Infrastructure.WebRoot": "G:\result20171120"
} 
"@

While $config is:

{
    "Common.BinDir": "G:\result",
    "Infrastructure.WebRoot": "G:\result20171120"
}

Below would work in Your case (although there must be better way to do it)

$abc = ConvertFrom-Json 
($decodedConfig($decodedConfig.Replace('@"','')).replace('"@',''))

2) You need to mask \\ in .Json files , so effectively You need to use \\\\ so in fact it Your Json should look like this:

@"
{
    "Common.BinDir": "G:\\result",
    "Infrastructure.WebRoot": "G:\\result20171120"
} 
"@

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM