如何在PowerShell中将哈希表正确转换为JSON?
我正在使用PowerShell向如何在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" }
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消息中。