代码之家  ›  专栏  ›  技术社区  ›  user2934433

Powershell convertfrom-转换为base64后出现Json错误

  •  -1
  • user2934433  · 技术社区  · 7 年前

    我试图在powershell中执行以下操作,但出现了一个无法找出原因的错误。

    以下工作正常

    $config = @"
    {
        "Common.BinDir": "G:\result",
        "Infrastructure.WebRoot": "G:\result20171120"
    }
    "@
    
    $abc = ConvertFrom-Json $testconfig
    

    但当我传入上面的base64时(因为我使用的脚本需要base64)

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

    运行convert命令时出现以下错误

    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
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Tomek    7 年前

    我相信有两件事
    1) 从base64解码的字符串包含@“和”@-作为字符串的一部分,而不是限定符-因此

    $decodedString 是:

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

    虽然 $config 是:

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

    以下内容适用于您的情况(尽管必须有更好的方法)

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

    2) 你需要掩饰 \ 在里面Json文件,因此您需要有效地使用 \\ 事实上,你的Json应该是这样的:

    @"
    {
        "Common.BinDir": "G:\\result",
        "Infrastructure.WebRoot": "G:\\result20171120"
    } 
    "@
    
        2
  •  1
  •   JosefZ    7 年前

    以下代码段应按预期在给定的 $config :

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