PowerShell for Windows Admins

Aug 19 2015   10:03AM GMT

Creating JSON from a hash table

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
JSON
Powershell

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”
}
]
}

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: