How do I correctly convert a HashTable to JSON in PowerShell?
The ConvertTo-Json cmdlet has a -depth
parameter which:
Specifies how many levels of contained objects are included in theJSON representation. The default value is 2.
Thus, you have to increase it:
$body | ConvertTo-Json -Depth 4
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 :)