我正在使用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()
实现。如何获得正确的输出?
最佳答案
ConvertTo-Json cmdlet具有-depth
参数:
Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.
因此,您必须增加它:
$body | ConvertTo-Json -Depth 4
关于json - 如何在PowerShell中将HashTable正确转换为JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38012564/