How to convert HashTable to JSON in PowerShell?

I use PowerShell to send a POST request to the REST API . The request body is as follows:

 { "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 generates 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 not commented out) produces the correct output, however line 7 creates:

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

}

It obviously HashTable type name HashTable , which is the default implementation of ToString() , which I assume. How to get the right result?

+5
source share
2 answers

The ConvertTo-Json cmdlet has the -depth parameter, which:

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

Thus, you should increase it:

 $body | ConvertTo-Json -Depth 4 
+7
source

This gives the desired JSON output:

 @{ 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 work without Martin Brandle’s advice, though :)

0
source

All Articles