json - 用于提供 Invoke-Restmethod 的动态 Json 变量

标签 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函数,然后找到保存“\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/

相关文章:

javascript - 嵌套的 JSON.parse 错误和 JS 对象遍历错误未被 JS try/catch 捕获,导致服务器崩溃

json - 否定 ?& JSON 运算符

java - Android 解码 PHP 文件编码的 JSON

powershell - 为什么 powershell 提示注释行?

json - PowerShell:如何将哈希表输出为 json 并使用 foreach 循环将其存储在变量中?

python - 从 Django 模型生成分层 JSON 树结构

powershell - 遍历哈希表中的日期?

azure - 用于访问 Azure 存储的 Com 互操作 DLL

git - 在 Azure 云服务中使用 LibGit2Sharp

java - azure 函数在 IntelliJ IDEA 中调试错误