H Bala H Bala - 5 months ago 36
JSON Question

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
causes the json to break. I tried to pipe to
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
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