Home > OS >  Powershell: Using Invoke-WebRequest, How To Use Variable Within JSON?
Powershell: Using Invoke-WebRequest, How To Use Variable Within JSON?

Time:05-29

Using Powershell, I'm trying to PUT data into an API, but I'm having trouble using a variable within the JSON:

This code below does not generate an error from the API, but it PUTS the singer as, literally, "$var_currentsinger" and doesn't use the intended variable

$currentsinger = "Michael Jackson"
$headers.Add("Content-Type", "application/json")
$response = Invoke-WebRequest -Uri https://stackoverflow.com -Method PUT -Headers $headers -Body '{
  "album": {
    "name": "Moonlight Sonata",
    "custom_fields": [{
      "singer": "$currentsinger",
      "songwriter": "Etta James"
    }]
  }
}'

This version below does not work, I assume because there are no quotes around the singer name. The API returns a value that the data is invalid

$currentsinger = "Michael Jackson"
$headers.Add("Content-Type", "application/json")
$response = Invoke-WebRequest -Uri https://stackoverflow.com -Method PUT -Headers $headers -Body '{
  "album": {
    "name": "Moonlight Sonata",
    "custom_fields": [{
      "singer": $currentsinger,
      "songwriter": "Etta James"
    }]
  }
}'

The only thing I have tried is double quotes and triple quotes around the variable, but I either get the $currentsinger variable within the JSON and have it submit the variable value and not the variable name.

CodePudding user response:

JSON requires double-quotes, so one example way to handle is by escaping the quotes or with a double-quoted here-string:

# here-string
$json = @"
  "singer": $currentsinger,
  "songwriter": "Etta James"
"@

# escaped
$json = "
  `"singer`": $currentsinger,
  `"songwriter`": `"Etta James`"
"
  • Related