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

问题描述 投票:9回答:2

我正在使用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()实现。 如何获得正确的输出?

json powershell
2个回答
13
投票

ConvertTo-Json cmdlet有一个-depth参数:

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

因此,你必须增加它:

$body | ConvertTo-Json -Depth 4

1
投票

这给出了你想要的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的建议,不会有用,但:)

© www.soinside.com 2019 - 2024. All rights reserved.