简体   繁体   English

动态Json变量以提供Invoke-Rest方法

[英]Dynamic Json variable to feed Invoke-Restmethod

I was able to pass the dynamic json object if the object creation code is in single line. 如果对象创建代码在一行中,则我可以传递动态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"

Since the dynamic JSON object in real world need be longer, I seperated created with new line and referenced in the above as below. But new line shift 由于现实世界中的动态JSON对象需要更长的时间,因此我用新行单独创建了该对象, and referenced in the above as below. But new line shift and referenced in the above as below. But new line shift causes the json to break. and referenced in the above as below. But new line shift会导致json中断。 I tried to pipe to ConvertTo-Json function and then found the output to hold '`\\r\\n' getting introduced: 我试图通过管道传递到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"

Note: The above works if the $body is single line. 注意:如果$body为单行,则上述方法适用。

How to approach in such scenarios where we create a dynamic json , long file and feed? 在创建动态json,长文件和提要的情况下,该如何处理?

Your example doesn't work because the last line containing a backtick which you have to omit. 您的示例无效,因为最后一行包含必须省略的反引号

You could use a here string to define your JSON so you don't need to seperate each line by a backtick: 您可以使用here字符串定义JSON,因此您不需要用反引号分隔每行:

$body = 
@' 
    { "name" : "azurefunctionapp2email",
       "appname": "Applicationnamehere",
       "requestedBy" : "requestedby",
       "reqdate" : "requestdate", 
       "status" : "Successfully Deployed", 
       "AppsCount" : "2" }
'@

You could also consider to use a PowerShell hashtable to define your object which will allows you to use variables without the need of a format string: 您还可以考虑使用PowerShell哈希表来定义您的对象,该对象将允许您使用变量而无需格式字符串:

$bodyObject = @{
    name = 'azurefunctionapp2email'
    appname = 'Applicationnamehere'
    requestedBy = 'requestedby'
    reqdate = 'requestdate'
    status = 'Successfully Deployed'
    AppsCount = '2'
}

$bodyObject | ConvertTo-Json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM