I'm looking to recursively sort the output of ConvertFrom-JSON. So I wrote the code below.
PowerShell
set-alias new New-Object
function Sort-JSONInternal()
{
param
(
[switch]
$bDontRecurse,
[parameter(Mandatory, Position=0, ValueFromPipeline)]
[ValidateNotNull()]
[object]
$json
)
$propertiesForCurJson = $json | Get-Member -type NoteProperty;
if($propertiesForCurJson.Count -eq 0)
{
write-output $json;
}
else
{
$ordered = [ordered]@{}
foreach($curEntry in $propertiesForCurJson | sort "Name")
{
$strNameOfCurProp = $curEntry.Name;
$curVal = $json.$($strNameOfCurProp);
if($curVal -eq $null)
{
$ordered[$strNameOfCurProp] = $curVal;
}
elseif($bDontRecurse)
{
$ordered[$strNameOfCurProp] = $json.$($curEntry.Name);
}
else
{
$ordered[$strNameOfCurProp] = Sort-JSONInternal $curVal;
}
}
$jsonSorted = new "PSCustomObject";
Add-Member -InputObject $jsonSorted -NotePropertyMembers $ordered;
write-output $jsonSorted;
}
}
function Sort-JSON()
{
param
(
[switch]
$bDontRecurse,
[parameter(Mandatory, Position=0, ValueFromPipeline, ValueFromRemainingArguments)]
[ValidateNotNullOrEmpty()]
[object[]]
$listOfJsonObj
)
$listOfJsonObj | foreach {write-output ($_ | Sort-JSONInternal -bDontRecurse:$bDontRecurse)};
}
But the function doesn't seem to work correctly. You call Sort-JSON with one or more JSON objects. Sort-JSONInternal does the actual sorting. If I have code below:
JSON
{
"t"; [ {"s": 3}, {"s": 5}]
}
It returns something more like:
JSON
{
"t": {"s": [3, 5]}
}
That's wrong. It shouldn't be summarizing the properties.
Can you tell me what's wrong?