如何打印JSON输出排序的对象数组?我的$result对象必须保持原样,即"Good"或";糟糕的;无所谓,我试着对数组中的对象进行排序按计数排序属性。
我代码:
$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)
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
的值:
- 使用
$data.Good += $food
创建一个新的数组(!),$food
在末尾,然后将其分配给$data.Good
。($data.Good = $data.Good + $food
的简写) - 使用
$data.Good = $data.Good | Sort-Object count
以不同的顺序创建一个新的数组,然后将其分配给$data.Good
。
嘿,我猜你忘记在Sort-Object后添加-Property了即
$sortGood = $result.Good | Sort-Object -Property count
试一试,让我知道!
我会这样做:
ConvertTo-Json @{
Good = $result.Good | sort Count
Bad = $result.Bad | sort Count
}