4

我有一个以数组为值的 JSON 文件,我想将数组排序为值。

测试.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"
                 }
             ]
}

如何对数组“汽车”进行排序以获得正确的顺序“奥迪”、“宝马”、“大众”?

4

2 回答 2

4

您需要对cars属性的值进行排序并将排序结果分配回属性:

$json = Get-Content '.\test.json' | ConvertFrom-Json
$json.cars = $json.cars | Sort-Object name
$json | ConvertTo-Json
于 2019-01-14T09:10:16.317 回答
1
$json = @"
{
  "user_name":  "paul",
  "cars":  [
               {
                   "name":  "BMW"
               },
               {
                   "name":  "VW"
               },
               {
                   "name":  "Audi"
               }
           ]
}
"@

$obj = ConvertFrom-Json $json
$obj.cars | Sort-Object {$_.name} | ConvertTo-Json
于 2019-01-14T09:12:15.217 回答