gpt4 book ai didi

json - Powershell 按字母顺序对 PSObject 进行排序

转载 作者:行者123 更新时间:2023-12-03 00:34:58 24 4
gpt4 key购买 nike

给定一个从 json (foo.json) 创建的自定义 powershell 对象 (bar)

您将如何按字母顺序对对象进行排序?

foo.json
{
"bbb": {"zebras": "fast"},
"ccc": {},
"aaa": {"apples": "good"}
}

期望的输出

foo.json
{
"aaa": {"apples": "good"},
"bbb": {"zebras": "fast"},
"ccc": {}
}

例子

$bar = get-content -raw foo.json | ConvertFrom-Json  
$bar.gettype()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object

我使用 sort-object 尝试了以下操作

$bar = $bar |排序
$bar = $bar |排序对象
Sort-Object -InputObject $bar
Sort-Object -InputObject $bar -Property Name
Sort-Object -InputObject $bar -Property @{Expression="Name"}
Sort-Object -InputObject $bar -Property @{Expression={$_.PSObject.Properties.Name}}

我还尝试将 PSObject 转换为哈希表(哈希表似乎会根据名称自动排序),然后将该哈希表转换回 json,但它再次失去了顺序。

$buzz = @{}
$bar.psobject.properties |Foreach { $buzz[$_.Name] = $_.Value }
ConvertTo-Json $buzz -Depth 9

更新
更改 foo.json 以包含值和键

最佳答案

作为 Mathias R. Jessen注意,这里没有要排序的collection,只有一个要排序的对象其属性,所以你需要reflection via Get-Member 获取对象的属性:

$bar = get-content -raw foo.json | ConvertFrom-Json

# Build an ordered hashtable of the property-value pairs.
$sortedProps = [ordered] @{}
Get-Member -Type NoteProperty -InputObject $bar | Sort-Object Name |
% { $sortedProps[$_.Name] = $bar.$($_.Name) }

# Create a new object that receives the sorted properties.
$barWithSortedProperties = New-Object PSCustomObject
Add-Member -InputObject $barWithSortedProperties -NotePropertyMembers $sortedProps

一个更精简的版本,它使用 -pv (-PipelineVariable) 来“缓存”由 ConvertFrom-Json 生成的未排序的自定义对象:

$barSortedProps = New-Object PSCustomObject
Get-Content -Raw foo.json | ConvertFrom-Json -pv jo |
Get-Member -Type NoteProperty | Sort-Object Name | % {
Add-Member -InputObject $barSortedProps -Type NoteProperty `
-Name $_.Name -Value $jo.$($_.Name)
}

关于json - Powershell 按字母顺序对 PSObject 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44056677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com