【问题标题】:Correctly format JSON for Powershell Post? (Missing '=' operator after key in hash literal.)为 Powershell Post 正确格式化 JSON? (散列文字中的键后缺少“=”运算符。)
【发布时间】:2021-11-17 20:29:30
【问题描述】:

我正在尝试使用 Powershell 执行一些“POST”请求。但是,我似乎无法正确格式化 JSON。我该如何做到这一点?

>> $JSON=@{name:"TestName"}
>> Invoke-WebRequest -Uri http://localhost:7071/api/HttpTrigger1 -Method POST -Body $JSON
>> $response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" -Method Post -Body $JSON -ContentType "application/json"

ParserError:
Line |
   1 |  $JSON=@{name:"TestName"}
     |              ~
     | Missing '=' operator after key in hash literal.

【问题讨论】:

  • $json = '{name:"TestName"}', @{ ... } 用于哈希表。

标签: powershell webrequest


【解决方案1】:

所以,有两种方法可以做到这一点:

按照圣地亚哥的建议,第一个是

$json = '{name:"TestName"}'
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
  -Method Post -Body $json -ContentType "application/json"

第二个,使用(大致)你使用的语法,是

#create a Powershell object (note the use of '=' instead of ':' for assignment)
#(such a simple example is not an improvement over the example above)
$json = @{ name = "TestName" } | ConvertTo-JSON 
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
  -Method Post -Body $json -ContentType "application/json"

第一种方法当然更干净、更直接。当请求的源数据来自操作 Powershell 对象的结果时,第二个很有用,并且您希望将它们转换为在 Web 请求中使用。

【讨论】:

  • 感谢圣地亚哥的编辑!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2020-02-03
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
相关资源
最近更新 更多