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

时间:2016-06-24 11:38:46

标签: json powershell

我正在使用PowerShell向POST发送REST API请求。请求正文如下:

{
  "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行产生:

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

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

2 个答案:

答案 0 :(得分:14)

ConvertTo-Json cmdlet具有-depth参数:

  

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

因此,你必须增加它:

$body | ConvertTo-Json -Depth 4

答案 1 :(得分:2)

这提供了您想要的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的建议,那就不会有用了。)