Creating JSON from a hash table

A question on the forum was asking about creating a JSON structure for use with a REST API.

The original has table looked like this

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

This fails because you can’t have duplicate keys in a hash table. 

One way to create the JSON is like this

$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

which gives:

{
    “Items”:  [
                  {
                      “value”:  “OK”,
                      “label”:  “server1”
                  },
                  {
                      “value”:  “OK”,
                      “label”:  “server2”
                  }
              ],
    “auth_token”:  “”
}

The items are created by adding hah tables to a pre-existing hash table.  You’re creating a hashtable of hash tables.

If you need to control the order of values you need an ordered hash table to use with New-Object

$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

which gives

{
    “auth_token”:  “”,
    “Items”:  [
                  {
                      “value”:  “OK”,
                      “label”:  “server1”
                  },
                  {
                      “value”:  “OK”,
                      “label”:  “server2”
                  }
              ]
}

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s