Powershell sort PSObject alphabetically

Viewed 7333

Given a custom powershell object (bar) that is created from json (foo.json)

How would you sort the object alphabetically by key?

foo.json
{
  "bbb": {"zebras": "fast"},
  "ccc": {},
  "aaa": {"apples": "good"}
}

Desired output

foo.json
{
  "aaa": {"apples": "good"},
  "bbb": {"zebras": "fast"},
  "ccc": {}
}

Example

$bar = get-content -raw foo.json | ConvertFrom-Json  
$bar.gettype()  

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    PSCustomObject                           System.Object

I've tried the following using sort-object

$bar = $bar | Sort
$bar = $bar | Sort-Object
Sort-Object -InputObject $bar
Sort-Object -InputObject $bar -Property Name
Sort-Object -InputObject $bar -Property @{Expression="Name"}
Sort-Object -InputObject $bar -Property @{Expression={$_.PSObject.Properties.Name}}

I've also tried converting the PSObject to a hashtable (hashtables appear to automatically sort based on name), then convert that hashtable back to json, but it looses the order again.

$buzz = @{}
$bar.psobject.properties |Foreach { $buzz[$_.Name] = $_.Value }
ConvertTo-Json $buzz -Depth 9

Update
Changed foo.json to include values aswell as keys

2 Answers

what about this:

Function Sort-PSObject {
        [CmdletBinding()]
        Param(
            [Parameter(ValueFromPipeline=$true)]$inputString
        )
        process {
            ($inputString | out-string).trim() -split "`r`n" | sort
        }
}

Can send direct from pipeline

Related