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.
-Body @" .... "@ConvertTo-Jsonas it will handle a whole multitude of edge-case for you - for example, what if$currentsinger = “James `”Godfather of Soul`” Brown”- you’d end up with invalid json by just interpolating the variable value into a json string