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"?
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