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

25

我正在使用PowerShell向REST API发送一个POST请求。请求的消息体如下:

{
  "title": "game result",
  "attachments": [{
      "image_url": "http://contoso/",
      "title": "good work!"
    },
    {
      "fields": [{
          "title": "score",
          "value": "100"
        },
        {
          "title": "bonus",
          "value": "50"
        }
      ]
    }
  ]
}

现在,以下 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 

若取消注释,第3行会输出正确的结果,然而第7行会产生:

Line 3 (if uncommented) produces the correct output, however line 7 produces:

{
  "attachments": [{
      "image_url": "http://contoso",
      "title": "good work!"
    },
    {
      "fields": "System.Collections.Hashtable System.Collections.Hashtable"
    }
  ],
  "title": "game result"
}

显然,它写出了HashTable的类型名称,这是默认的ToString()实现,我猜想如此。
我该如何获得正确的输出?

2个回答

40

ConvertTo-Json 命令有一个 -depth 参数,它:

指定 JSON 表示中包含多少级包含对象。默认值为 2。

因此,您需要将其增加:

$body | ConvertTo-Json -Depth 4

1
非常有帮助!我正在编写一个PowerShell活动,用于Azure OMS自动化图形运行簿向Slack频道发送消息。 - srbrills
@srsedate,你有没有遇到在Slack中根本没有显示字段的情况?即使按照这里详细说明的更改方式,它们对于我来说也没有在Slack消息中显示出来。 - Rob Segal

9
这将提供您所需的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

没有 Martin Brandl 的建议,这个工作就不可能完成 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接