Invoke-RestMethod JSON format

Welcome Forums General PowerShell Q&A Invoke-RestMethod JSON format

Viewing 1 reply thread
  • Author
    • #191806
      Topics: 2
      Replies: 3
      Points: 42
      Rank: Member

      I’m trying to post the following json``

      "close_code":"Not Solved",
      "close_notes":"Not solved"

      To do so I’m using:

      [email protected]{
      "records"[email protected]{
      "close_code"="Solved (With Request)";
      "close_notes"="Auto Closing Multiple Tickets" 
      $json = $body | convertto-json
      $result=try { Invoke-RestMethod -Uri $qa -Credential $credentials -Method Put -Body $json -ContentType "application/json" } 
      catch [Exception] {
                  Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
                  Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription

      But I am receiving a 400 Bad Request error.

      That json return the following if you display the json variable.

      "records": {
      "close_notes": "Auto Closing Multiple Tickets",
      "close_code": "Solved (With Request)",
      "inc_number": "INC002580523"

      Which I am assuming is malformed json for this service.

      Anyone have a suggestion the proper way to format the json above. The api specified that this how it should be sent. Thank you.

    • #191848
      Topics: 0
      Replies: 24
      Points: 158
      Helping Hand
      Rank: Participant

      You are not creating an array. You are creating a nested hashtable. Try this:

      PS> $records = @(
            close_code='Solved (With Request)'
            close_notes='Auto Closing Multiple Tickets'
      PS> $body = New-Object PSObject -Property @{records = $records} | ConvertTo-JSON
      PS> $body
        "records": [
            "inc_number": "INC002580523",
            "close_notes": "Auto Closing Multiple Tickets",
            "close_code": "Solved (With Request)"

      Note that the outer container is an array. Also note, you do not need the semicolons or quotes around the member names. Here is the result


Viewing 1 reply thread
  • The topic ‘Invoke-RestMethod JSON format’ is closed to new replies.