header image

Creating JSON from a hash table

Posted by: | August 19, 2015 Comments Off on 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"
                  }
              ]
}

under: PowerShell Basics

Comments are closed.

Categories