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?
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
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With