如何在PowerShell中将HashTable正确转换为JSON?

Roe*_*elF 12 powershell json

我正在使用PowerShell向a发送POST请求REST API.请求的主体如下所示:

{
  "title": "game result",
  "attachments": [{
      "image_url": "http://contoso/",
      "title": "good work!"
    },
    {
      "fields": [{
          "title": "score",
          "value": "100"
        },
        {
          "title": "bonus",
          "value": "50"
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

现在,以下PowerShell脚本生成错误的输出:

$fields = @(@{title='score'; value='100'},@{title='bonus'; value='10'})
$fieldsWrap = @{fields=$fields}
#$fieldsWrap | ConvertTo-Json
$attachments = @(@{title='good work!';image_url='http://contoso'},$fieldsWrap)
$body = @{title='game results';attachments=$attachments}
$json = $body | ConvertTo-Json
$json 
Run Code Online (Sandbox Code Playgroud)

第3行(如果未注释)产生正确的输出,但是第7行产生:

{
  "attachments": [{
      "image_url": "http://contoso",
      "title": "good work!"
    },
    {
      "fields": "System.Collections.Hashtable System.Collections.Hashtable"
    }
  ],
  "title": "game result"
}
Run Code Online (Sandbox Code Playgroud)

它显然写出了类型名称HashTable,这是ToString()我假设的默认实现.
如何获得正确的输出?

Mar*_*ndl 18

的ConvertTo JSON的 cmdlet都具有一个-depth参数,该参数:

指定JSON表示中包含的包含对象的级别数.默认值为2.

因此,你必须增加它:

$body | ConvertTo-Json -Depth 4
Run Code Online (Sandbox Code Playgroud)


sod*_*low 8

这给出了你想要的 JSON 输出:

@{
    title = "game result"    
    attachments =  @(
        @{
            image_url = "http://contoso/"
            title = "good work!"
        },
        @{
            fields = @(
                @{
                    title = "score"
                    value = "100"
                },
                @{
                    title = "bonus"
                    value = "50"
                }
            )
        }
    )
} | ConvertTo-Json -Depth 4
Run Code Online (Sandbox Code Playgroud)

不过,如果没有 Martin Brandl 的建议,就不会奏效:)