簡體   English   中英

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://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:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM