简体   繁体   中英

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

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.

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`"
"

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