Powershell:使用Invoke-WebRequest,如何使用JSON内的变量?

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

使用 Powershell,我试图将数据放入 API,但我在 JSON:

中使用变量时遇到问题

下面的代码不会从 API 生成错误,但它会将 singer 按字面意思表示为“$var_currentsinger”,并且不会使用预期的变量

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

下面的这个版本不起作用,我假设是因为 singer 名称周围没有引号。 APIreturns一个值表示数据无效

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

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

JSON 需要 double-quotes,因此一种示例处理方法是转义引号或使用 double-quoted here-string:

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

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