Powershell 转换为 Json 格式错误

Mar*_*ous 3 powershell json ansible

我正在使用 win_shell 将 powershell 输出转换为 json 格式,以便稍后可以对其进行过滤。问题是我的 Json 格式很糟糕。

这是代码

    - win_shell: |
         Get-ChildItem -Path <some_path> |
         Where-Object {$_.PSIsContainer} | Sort-Object LastWriteTime -Descending |
         Select-Object -First 20 | ConvertTo-Json
         register: register_results

     - debug:
         var: register_results
Run Code Online (Sandbox Code Playgroud)

我得到的标准输出行不干净,无法在 json 过滤器中使用:

  "stderr": "",
  "rc": 0,
  "stdout_lines": [
      "[",
      "    {",
      "        \"Name\":  \"976\",",
      "  \"FullName\"\"F:\\\\some\\\\path\\\\to\\\\folder\\\\976\",",
      "  \"Parent\":  {",
      "                       \"Name\":  \"first\",",
      "                       \"Parent\":  \"All\",",
      "                       \"Exists\":  true,",
      "                       \"Root\":  \"F:\\\\\",",
      "                       \"Extension\":  \"\",",
      etc...
Run Code Online (Sandbox Code Playgroud)

当我尝试过滤“父级”或“名称”时,这些额外的空格会导致错误。看起来除了“ConvertToJson”之外还必须有其他参数才能使输出更清晰。

有办法做到这一点吗?

Kod*_*ody 5

根据这篇文章ConvertTo-Json,计划在 PowerShell 6 中改进JSON 格式。您可以ConvertTo-Json像文章建议的那样自行覆盖格式。提到的帖子中的一些代码可能会解决您的问题:

# Formats JSON in a nicer format than the built-in ConvertTo-Json does.
function Format-Json([Parameter(Mandatory, ValueFromPipeline)][String] $json) {
  $indent = 0;
  ($json -Split '\n' |
    % {
      if ($_ -match '[\}\]]') {
        # This line contains  ] or }, decrement the indentation level
        $indent--
      }
      $line = (' ' * $indent * 2) + $_.TrimStart().Replace(':  ', ': ')
      if ($_ -match '[\{\[]') {
        # This line contains [ or {, increment the indentation level
        $indent++
      }
      $line
  }) -Join "`n"
}

$obj = @{}
$json = $obj | ConvertTo-Json | Format-Json
Run Code Online (Sandbox Code Playgroud)

或者,您应该能够通过安装和导入模块来直接使用ConvertTo-JsonNewtonsoftNewtonsoft.JsonConvertTo-Json并使用它而不是...

Install-Module Newtonsoft.Json
Import-Module Newtonsoft.Json

$obj = @{}
$json = $obj | ConvertTo-JsonNewtonsoft

# or Newtonsoft.Json directly (same code)

$obj = @{}
$json = [Newtonsoft.Json.JsonConvert]::SerializeObject($obj, [Newtonsoft.Json.Formatting]::Indented)
Run Code Online (Sandbox Code Playgroud)

  • +1 指出它在 v6 及更高版本中得到了改进。我切换到 Powershell Core,它非常完美! (3认同)