Home > Net >  Correctly format JSON for Powershell Post? (Missing '=' operator after key in hash literal
Correctly format JSON for Powershell Post? (Missing '=' operator after key in hash literal

Time:11-18

I am attempting to use Powershell to perform some "POST" requests. However, I can't seem to get the JSON correctly formatted. How do I accomplish this?

>> $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.

CodePudding user response:

So, there are two ways you can do this:

The first, as suggested by Santiago, is

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

The second, using (roughly) the syntax you were using, is

#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"

The first method is certainly cleaner and more direct. The second is useful when the source data for the request comes as the result of manipulating Powershell objects, and you want to convert them for use in a web request.

  • Related