How to sort an object by keys using powershell

时间:2018-03-09 19:11:39

标签: json powershell sorting

I have the following json file and I want it sorted by the keys/names. But so far I have been unable to figure out how to actually sort the json object by it's key/name.

Origional Settings.json

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

Code:

# 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

New Settings.Json

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

2 个答案:

答案 0 :(得分:1)

答案在这里:Powershell sort PSObject alphabetically

这个问题是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

答案 1 :(得分:-1)

$json | Select-Object ($json | Get-Member -MemberType NoteProperty).Name | ConvertTo-Json
相关问题