我正在尝试向需要主体为json数组的API发送请求。如何将参数哈希表转换为json数组?
$parameters =@{
"sn" = "CND3210W9M"
"pn" = "D5H49AV"
}
$post = Invoke-RestMethod -Uri "https://blah.com/queries" -Method Post -Body ($parameters | ConvertTo-Json) -Headers $headers -ContentType 'application/json'
API示例将下面的数组显示为有效正文
[
{
"sn": "CND3210W9M",
"pn": "D5H49AV"
}
]
答案 0 :(得分:0)
如果您的请求期望有效的json,它可能看起来像这样:
$body = @{
parameters =
@( # Make this an array
@{ # of hashtables
"sn" = "CND3210W9M"
"pn" = "D5H49AV"
} ) }
$body | ConvertTo-Json
输出:
{
"parameters": [
{
"pn": "D5H49AV",
"sn": "CND3210W9M"
}
]
}
答案 1 :(得分:0)
@Eris,我尝试使用你的代码,但它返回了额外的{},这是API不喜欢的。
最后,我最终只使用了一个字符串并继续前进。它不是很优雅,但无法让API正确响应。
$body = @"
[
{
"sn": "$sn",
"pn": "$pn"
}
]
"@