H Bala H Bala - 1 year ago 109
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download