Posting using Invoke-RestMethod to a list on Dashing

Hi,

I am trying to get the curl below translated into powershell. I am fairly sure it is the formatting of the $body but I am not having much luck at figuring it out myself.

The curl line:

curl -d '{ "auth_token":"uubiegoviogiePhohlaexei7ab2beebe", "items": [ {"label": "server1", "value": "OK"}, {"label": "server2", "value": "OK"} ] }' http://dashing.domain.tld/widgets/servers

What I have:

$proxyserver = "http://proxy.domain.tld:3128"
$auth_token = "MyAuthToken"
$dashing = "http://dashing.domain.tld/widgets/servers"

$body = @{
    auth_token = "$auth_token"
    items = @{
        label = "server1"
        value = "OK"
        label = "server2"
        value = "OK"
        }
    }

Invoke-RestMethod -Proxy $proxyserver -Uri "$dashing" -Method Post -Body (ConvertTo-Json $body)

Any help will be appreciated

Thanks

Kim

If you just look at the conversion of your hash table to json

$body = @{
auth_token = “$auth_token”
items = @{
label = “server1”
value = “OK”
label = “server2”
value = “OK”
}
}

ConvertTo-Json -InputObject $body

I got this error

At line:6 char:9

  •     label = "server2"
    
  •     ~~~~~
    

Duplicate keys ‘label’ are not allowed in hash literals.
At line:7 char:9

  •     value = "OK"
    
  •     ~~~~~
    

Duplicate keys ‘value’ are not allowed in hash literals.
+ CategoryInfo : ParserError: (:slight_smile: [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : DuplicateKeyInHashLiteral

In a hash table all of your keys must be unique.

The json doesn’t form so your call to the web service fails

Try this to create your JSON

$items = @()
$items += @{label = “server1”; value = “OK”}
$items += @{label = “server2”; value = “OK”}

$body = New-Object -TypeName PSOBject -Property @{
auth_token = “$auth_token”
Items = $items
}

ConvertTo-Json -InputObject $body

If you need to dictate the order of properties in the JSON

$items = @()
$items += @{label = “server1”; value = “OK”}
$items += @{label = “server2”; value = “OK”}

$props = [ordered]@{
auth_token = “$auth_token”
Items = $items
}

$body = New-Object -TypeName PSOBject -Property $props

ConvertTo-Json -InputObject $body

Hi Richard,

Thanks, I will try those in the morning when I get to the office

Hi Richard,

Thank you so much, that works like a bomb :slight_smile:

I also needed to add -ContentType “application/json” to my invoke-RestMethod command I am now updating the dashboard as expected.