我正在使用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()
实现。
如何获得正确的输出?
答案 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的建议,那就不会有用了。)