powershell sort json by value with Sort-Object

9.1k Views Asked by At

I have a JSON file with an array as value and I would like to sort the array be value.

test.json

{
    "user_name" : "paul",
    "cars" : 
    [
        {
            "name" : "BMW"
        },
        {
            "name" : "VW"
        },              
        {
            "name" : "Audi"
        }
    ]
}

My powershell command

Get-Content .\test.json | ConvertFrom-Json | Sort-Object -Property @{expression={$_.cars.name};Descending=$true} | ConvertTo-Json
{
    "user_name":  "paul",
    "cars":  [
                 {
                     "name":  "BMW"
                 },
                 {
                     "name":  "VW"
                 },
                 {
                     "name":  "Audi"
                 }
             ]
}

How can I sort the array "cars" to get the correct order "Audi", "BMW", "VW"?

2

There are 2 best solutions below

0
On BEST ANSWER

You need to sort the value of the cars property and assign the sorted result back to the property:

$json = Get-Content '.\test.json' | ConvertFrom-Json
$json.cars = $json.cars | Sort-Object name
$json | ConvertTo-Json
0
On
$json = @"
{
  "user_name":  "paul",
  "cars":  [
               {
                   "name":  "BMW"
               },
               {
                   "name":  "VW"
               },
               {
                   "name":  "Audi"
               }
           ]
}
"@

$obj = ConvertFrom-Json $json
$obj.cars | Sort-Object {$_.name} | ConvertTo-Json