arrays - PowerShell - 使用已排序的对象数组打印 JSON 输出?
问题描述
如何使用已排序的对象数组打印 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?(水果按“count”属性升序排序)
{
"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
and的值$data.Bad
:
- 使用在末尾
$data.Good += $food
创建一个新数组(!)$food
,然后将其分配给$data.Good
. (它是 . 的简写$data.Good = $data.Good + $food
。) - 使用
$data.Good = $data.Good | Sort-Object count
以不同的顺序创建一个新数组(!),然后将其分配给$data.Good
.
推荐阅读
- reactjs - 在 ES6 和 React 中随时间返回多个值
- php - 如何通过按钮/变量增加天数?
- sap-cloud-sdk - 构建maven项目s4hana cloud sdk时出错
- apache-kafka - Kafka 偏移量和分区识别
- android - Android Realm - 无法在路径打开领域:read_only 文件系统
- java - java清单中没有快捷目录文件夹的问题设置类路径
- xpath - xpath 如何提取元素本身及其子元素之一?
- arrays - 如何在 matlab 上将字符串添加到数组的开头?
- pandas - Groupby diff() 日期,groupby 大小并检查 pandas 中其他列的序列
- python - 按表示相同值的多个键对字典进行排序