动态Json变量来提供Invoke-Restmethod

时间:2016-08-02 05:30:39

标签: json powershell azure

如果对象创建代码是单行,我能够传递动态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函数,然后发现输出保持'\ n \ 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的情况下进行处理?

1 个答案:

答案 0 :(得分:2)

您的示例不起作用,因为最后一行包含反引号,您必须省略它。

您可以使用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