Invoke-RestMethod JSON format

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

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

      I'm trying to post the following json``

      {"records":[
      
      {
      
      "inc_number":"INC0010792",
      
      "close_code":"Not Solved",
      
      "close_notes":"Not solved"
      
      }
      
      ]
      
      }

      To do so I'm using:

      $body=@{
      "records"=@{
      "inc_number"="INC002580523";
      "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
      Participant
      Topics: 0
      Replies: 23
      Points: 152
      Helping Hand
      Rank: Participant

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

      PS> $records = @(
          @{ 
            inc_number='INC002580523'
            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
  • You must be logged in to reply to this topic.