繁体   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