25

I'm using PowerShell to send a POST request to a REST API. The body of the request looks like this:

{
  "title": "game result",
  "attachments": [{
      "image_url": "http://contoso/",
      "title": "good work!"
    },
    {
      "fields": [{
          "title": "score",
          "value": "100"
        },
        {
          "title": "bonus",
          "value": "50"
        }
      ]
    }
  ]
}

Now, the following PowerShell script produces the wrong output:

$fields = @(@{title='score'; value='100'},@{title='bonus'; value='10'})
$fieldsWrap = @{fields=$fields}
#$fieldsWrap | ConvertTo-Json
$attachments = @(@{title='good work!';image_url='http://contoso'},$fieldsWrap)
$body = @{title='game results';attachments=$attachments}
$json = $body | ConvertTo-Json
$json 

Line 3 (if uncommented) produces the correct output, however line 7 produces:

{
  "attachments": [{
      "image_url": "http://contoso",
      "title": "good work!"
    },
    {
      "fields": "System.Collections.Hashtable System.Collections.Hashtable"
    }
  ],
  "title": "game result"
}

It obviously writes out the type name of the HashTable, which is the default ToString() implementation I assume.
How do I get the correct output?

2 Answers 2

40

The ConvertTo-Json cmdlet has a -depth parameter which:

Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.

Thus, you have to increase it:

$body | ConvertTo-Json -Depth 4
2
  • 1
    So helpful! I was writing a PowerShell activity for an Azure OMS Automation graphical runbook to send a message to a Slack channel.
    – srbrills
    Sep 5, 2017 at 16:26
  • @srsedate did you experience the fields not showing up at all in Slack? Even with the changes detailed here which have been helpful I don't see them show up in the Slack message.
    – Rob Segal
    Aug 9, 2019 at 15:18
9

This gives the JSON output you want:

@{
    title = "game result"    
    attachments =  @(
        @{
            image_url = "http://contoso/"
            title = "good work!"
        },
        @{
            fields = @(
                @{
                    title = "score"
                    value = "100"
                },
                @{
                    title = "bonus"
                    value = "50"
                }
            )
        }
    )
} | ConvertTo-Json -Depth 4

Wouldn't have worked without Martin Brandl's advice, though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.