Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PowerShell中将哈希表正确转换为JSON?_Json_Powershell - Fatal编程技术网

如何在PowerShell中将哈希表正确转换为JSON?

如何在PowerShell中将哈希表正确转换为JSON?,json,powershell,Json,Powershell,我正在使用PowerShell向RESTAPI发送POST请求。请求主体如下所示: { "title": "game result", "attachments": [{ "image_url": "http://contoso/", "title": "good work!" }, { "fields": [{ "title": "score", "value": "100" }

我正在使用PowerShell向
RESTAPI
发送
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行生成:

{
  "attachments": [{
      "image_url": "http://contoso",
      "title": "good work!"
    },
    {
      "fields": "System.Collections.Hashtable System.Collections.Hashtable"
    }
  ],
  "title": "game result"
}
它显然写出了
HashTable
的类型名,这是我假定的默认
ToString()
实现。
如何获得正确的输出?

cmdlet有一个
-depth
参数,该参数:

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

因此,您必须增加它:

$body | ConvertTo-Json -Depth 4

这将提供您想要的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

不过,如果没有马丁·布兰德尔的建议,我是不会工作的:)

太有帮助了!我正在为Azure OMS Automation图形runbook编写一个PowerShell活动,以向Slack通道发送消息。@sr您是否体验到Slack中根本没有显示字段?即使这里详细介绍了一些有帮助的更改,我也没有看到它们出现在Slack消息中。