如何使用排序的物件陣列列印 JSON 輸出?我的 $result 物件必須保持原樣,“好”或“壞”的順序無關緊要,我試圖對按“count”屬性按升序排序的陣列中的物件進行排序。
我的代碼:
$result = [PSCustomObject]@{
Good = @()
Bad = @()
}
$food = [PSCustomObject]@{
name = "Banana"
count = 2
}
if ($food.count -gt 3) { $result.Good = $food }
else { $result.Bad = $food }
$sortGood = $result.Good | Sort-Object count
$sortBad = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)
我的 JSON 輸出是:
{
"Good": [
{
"name": "Apple"
"count": 10
},
{
"name": "Lime"
"count": 5
},
{
"name": "Peach"
"count": 7
}
],
"Bad": [
{
"name": "Banana"
"count": 2
},
{
"name": "Kiwi"
"count": 1
},
{
"name": "Orange"
"count": 3
}
]
}
如何列印看起來像這樣的 JSON?(水果按“計數”屬性升序排序)
{
"Good": [
{
"name": "Lime"
"count": 5
},
{
"name": "Peach"
"count": 7
},
{
"name": "Apple"
"count": 10
},
],
"Bad": [
{
"name": "Kiwi"
"count": 1
},
{
"name": "Banana"
"count": 2
},
{
"name": "Orange"
"count": 3
}
]
}
[問題已解決] 編輯的解決方案:
$result.Good = $result.Good | Sort-Object count
$result.Bad = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)
uj5u.com熱心網友回復:
Sort-Object不“排序物件”。它回傳物件的排序副本。所以這
$sortGood = $result.Good | Sort-Object count
將導致$sortGood正確排序,并$result.Good完全保持原樣。
$json = @"
{
"Good": [
{"name": "Apple", "count": 10},
{"name": "Lime", "count": 5},
{"name": "Peach", "count": 7}
],
"Bad": [
{"name": "Kiwi", "count": 1},
{"name": "Orange", "count": 4}
]
}
"@
$data = ConvertFrom-Json $json
$food = @{
name = "Banana"
count = 2
}
if ($food.count -gt 3) {
$data.Good = $food
} else {
$data.Bad = $food
}
$data.Good = $data.Good | Sort-Object count
$data.Bad = $data.Bad | Sort-Object count
$result = $data | ConvertTo-Json -Depth 10
$result
給
{
"Good": [
{
"name": "Lime",
"count": 5
},
{
"name": "Peach",
"count": 7
},
{
"name": "Apple",
"count": 10
}
],
"Bad": [
{
"name": "Kiwi",
"count": 1
},
{
"count": 2,
"name": "Banana"
},
{
"name": "Orange",
"count": 4
}
]
}
請注意,我總是重新分配的值$data.Good和$data.Bad:
- Using在末尾
$data.Good = $food創建一個新陣列 (!)$food,然后將其分配給$data.Good. (這是 的簡寫$data.Good = $data.Good $food。) - Using
$data.Good = $data.Good | Sort-Object count以不同的順序創建一個新陣列 (!),然后將其分配給$data.Good.
uj5u.com熱心網友回復:
嘿,我猜你忘了在 Sort-Object 之后添加 -Property ie
$sortGood = $result.Good | Sort-Object -Property count
試一試,讓我知道!!!
uj5u.com熱心網友回復:
我會這樣做:
ConvertTo-Json @{
Good = $result.Good | sort Count
Bad = $result.Bad | sort Count
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/334681.html
上一篇:如何從陣列列印類屬性?
