简体   繁体   中英

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.

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 and referenced in the above as below. But new line shift causes the json to break. I tried to pipe to ConvertTo-Json function and then found the output to hold '`\\r\\n' getting introduced:

$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.

How to approach in such scenarios where we create a dynamic json , long file and feed?

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:

$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:

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

$bodyObject | ConvertTo-Json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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