如何使用PowerShell按键对对象进行排序

3

我有以下的json文件,我想按照键/名称进行排序。但是到目前为止,我还无法弄清楚如何实际上通过它的键/名称对json对象进行排序。

原始的Settings.json

{
  "files.trimTrailingWhitespace": true,
  "workbench.startupEditor": "newUntitledFile",
  "editor.tabSize": 4,
  "editor.formatOnSave": true,
  "editor.detectIndentation": false,
  "editor.trimAutoWhitespace": true
}

代码:

# Get Json File
$JsonFile = 'C:\Settings.json'
# Convert from Json File to Json Object
$Json = Get-Content $JsonFile | Out-String | ConvertFrom-Json 
# Sort Json Object (Does Not Work!!!)
$Json = $Json | Sort-Object -Property Name
#Convert Json Object to Json File
$Json | ConvertTo-Json -depth 100 | Set-Content $JsonFile

新的 Settings.Json
{
  "editor.detectIndentation": false,
  "editor.formatOnSave": true,
  "editor.tabSize": 4,
  "editor.trimAutoWhitespace": true
  "files.trimTrailingWhitespace": true,
  "workbench.startupEditor": "newUntitledFile"
}

嗨,$Json | Sort-Object -Properties Name 显示已排序的行,但不会将它们存储为已排序。你需要在开头添加 $Json = 才能实现。 - sodawillow
1
或者只需将 Sort 添加到输出它的最后一行。 $Json | Sort -Properties Name | ConvertTo-Json -Depth 100 | Set-Content $JsonFile - TheMadTechnician
问题似乎在于 sort-object -property name 并没有实际对对象进行排序。 - Keith
3个回答

2

这里的答案是:如何使用PowerShell按字母顺序对PSObject进行排序

问题在于json文件没有集合可供排序,而是一个我想要排序其属性的单个对象。下面是可行的代码。

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

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

  $JsonFileSorted | ConvertTo-Json -depth 100 | Set-Content $JsonFile

2
$json | Select-Object ($json | Get-Member -MemberType NoteProperty).Name | ConvertTo-Json

5
最好能够提供一些解释,以便不仅仅是代码转储。这似乎依赖于“Get-Member”执行排序,这既不明显也没有记录在文档中。 - Lance U. Matthews
1
点赞,因为发布的代码对我有效且优雅,但我同意评论中提到的,解释会更好。 - Michael Buchoff

0

只是为了快速复制粘贴选项而概括一下

  $JsonFile = 'C:\data.json'
  $JSON = Get-Content $JsonFile | ConvertFrom-Json

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

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

  $JsonFileSorted | ConvertTo-Json -depth 100 | Set-Content $JsonFile

感谢 @Keith 的问题和回答

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接