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"
}
$Json | Sort-Object -Properties Namedisplays the sorted lines but does not store them sorted. You need to add$Json =at the beginning for that.Sortto the last line that outputs it.$Json | Sort -Properties Name | ConvertTo-Json -Depth 100 | Set-Content $JsonFilesort-object -property namedoes not actually sort the object.