Powershell:使用Invoke-WebRequest,如何在JSON中使用变量?



使用Powershell,我试图将数据放入API,但我在JSON中使用变量时遇到麻烦:

下面的代码不会从API生成错误,但是它会将singer放到"$var_currentsinger"并且没有使用预期的变量

$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"
}]
}
}'

下面这个版本不起作用,我认为是因为singer名称周围没有引号。API返回数据无效的值

$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"
}]
}
}'

我唯一尝试的是双引号和三引号周围的变量,但我要么得到JSON中的$currentsinger变量,并让它提交变量值,而不是变量名。

JSON需要双引号,因此处理的一个示例方法是通过转义引号或使用双引号来处理:

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

最新更新