过去几天,我一直在寻找有关JSON对象中变量扩展的文档。我尝试了很多建议和修正,但是似乎都没有达到预期的效果。我只是想知道是否有比我实现的更好的方法。无论如何,在我的用例上。
用例 我有一个整数数组,这些整数表示Web应用程序中的对象。通过向API端点发出POST请求,可以在这些对象之间建立关系。
此整数数组称为$combined
。
PS C:\> $combined
i_id m_id
------------ ----------
75419 6403
75420 6403
75421 6403
75410 6403
要设置用于POST请求的参数,我创建了另一个名为$associationParams
的数组。
$associationParams = @{
ContentType = "application/json"
Body = '{"id": '+$($thing).m_id+'}'
Method = "POST"
URI = "https://application/api/in/$($thing.i_id)/endpoint"
Headers = $headers
}
上面的$headers
变量是授权令牌。
因此,我最初的爱好是遍历整数数组($combined
)并按如下方式调用Invoke-RestMethod
:
Foreach ($thing in $combined) {
Invoke-RestMethod @iocAssociationParams
}
问题
因此,我本身并不是真正的问题。在我的测试中似乎存在一些不一致之处,即最终的ForEach
似乎并没有遍历$combined
数组中的所有元素...但是我想知道是否有更好的方法。我已经尝试在$associationParams
的Body参数中使用字符串格式格式化JSON对象,但是绝对不能正常工作。我也尝试过各种形式的报价,但是它们也不起作用。是否尝试以最佳方式喷洒Invoke-RestMethod
的参数?我是否应该只列出Invoke-RestMethod
循环中ForEach
的所有参数?
答案 0 :(得分:1)
使用-f
格式运算符将$thing.m_id
内的foreach
插入$AssociationParams
。
您必须通过加倍来避开字面大括号。
Foreach ($thing in $combined) {
$AssociationParams = @{
ContentType = "application/json"
Body = '{{"id": {0}}}' -f $thing.m_id
Method = "POST"
URI = "https://application/api/in/$($thing.i_id)/endpoint"
Headers = $headers
}
Invoke-RestMethod @AssociationParams
}
答案 1 :(得分:0)
这是我实施的解决方案。
Foreach ($thing in $combined) {
# Now we create the body of the request as a Powershell object with the intent to convert it to JSON later
$AssociationBodyObj = [PSCustomObject]@{
id = $($thing.id)
}
# ...and then we convert it to JSON
$AssociationBodyObj = $AssociationBodyObj | ConvertTo-Json
$iocAssociationParams = @{
ContentType = "application/json"
Body = $AssociationBodyObj
Method = "POST"
URI = "https://application/api/in/$($thing.i_id)/endpoint"
Headers = $headers
}
Invoke-RestMethod @AssociationParams
}