[英]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:使用 Powershell,我正在尝试将数据放入 API,但在使用 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下面的代码不会从 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"
}]
}
}'
This version below does not work, I assume because there are no quotes around the singer
name.下面的这个版本不起作用,我假设是因为
singer
名字周围没有引号。 The API returns a value that the data is invalid 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"
}]
}
}'
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 中获取 $currentsinger 变量,然后让它提交变量值而不是变量名。
JSON requires double-quotes, so one example way to handle is by escaping the quotes or with a double-quoted here-string: JSON 需要双引号,因此处理的一种示例方法是转义引号或使用双引号 here-string:
# here-string
$json = @"
"singer": $currentsinger,
"songwriter": "Etta James"
"@
# escaped
$json = "
`"singer`": $currentsinger,
`"songwriter`": `"Etta James`"
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.