powershell 使用 Sort-Object 按值排序 json

powershell sort json by value with Sort-Object

我有一个 JSON 文件,其中有一个数组作为值,我想将该数组排序为值。

test.json

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

我的 powershell 命令

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

如何对数组 "cars" 进行排序以获得正确的顺序 "Audi"、"BMW"、"VW"?

您需要对 cars 属性 的值进行排序,并将排序后的结果赋值给 属性:

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

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