Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly convert a HashTable to JSON in PowerShell?

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?

like image 968
RoelF Avatar asked Jun 24 '16 11:06

RoelF


2 Answers

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
like image 177
Martin Brandl Avatar answered Sep 23 '22 21:09

Martin Brandl


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 :)

like image 33
sodawillow Avatar answered Sep 22 '22 21:09

sodawillow