如果对象创建代码在单行中,我就能够传递动态 json 对象。
Invoke-RestMethod -ContentType "application/json" -Method Post -Body '{ "name" : "azurefunctionapp2email", "appname": "Applicationnamehere", "requestedBy" : "requestedby", "reqdate" : "requestdate", "status" : "Successfully Deployed", "AppsCount" : "2" }' `
-Uri “https://implementurihere"
由于现实世界中的动态JSON对象需要更长,所以我用新行and referenced in the above as below. But new line shift
单独创建导致 json 损坏。我尝试通过管道发送到 ConvertTo-Json
函数,然后找到保存“\r\n”的输出:
$body = '{ "name" : "azurefunctionapp2email", `
"appname": "Applicationnamehere", `
"requestedBy" : "requestedby", `
"reqdate" : "requestdate",
"status" : "Successfully Deployed",
"AppsCount" : "2" }' `
Invoke-RestMethod -ContentType "application/json" -Method Post -Body $body `
-Uri “https://implementurihere"
注意:如果 $body
则上述内容有效是单行。
在创建动态 json 、长文件和 feed 的情况下如何处理?
最佳答案
您的示例不起作用,因为您必须省略最后一行包含反引号。
您可以使用 here string定义 JSON,这样您就不需要用反引号分隔每一行:
$body =
@'
{ "name" : "azurefunctionapp2email",
"appname": "Applicationnamehere",
"requestedBy" : "requestedby",
"reqdate" : "requestdate",
"status" : "Successfully Deployed",
"AppsCount" : "2" }
'@
您还可以考虑使用 PowerShell 哈希表来定义对象,这将允许您使用变量而无需格式字符串:
$bodyObject = @{
name = 'azurefunctionapp2email'
appname = 'Applicationnamehere'
requestedBy = 'requestedby'
reqdate = 'requestdate'
status = 'Successfully Deployed'
AppsCount = '2'
}
$bodyObject | ConvertTo-Json
关于json - 用于提供 Invoke-Restmethod 的动态 Json 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38712384/