0

I'm trying to sort the following JSON objects by the value of the "Index" key.

JSON =  {           
        "PIPoint":  {
                        "Label":  "\"PIPoint\"",
                        "Visible":  "True",
                        "Index":  "2"
                    },
        "Description":  {
                            "Label":  "\"Description\"",
                            "Visible":  "True",
                            "Index":  "3"
                        },
        "Analysis":  {
                         "Label":  "\"Analysis\"",
                         "Visible":  "True",
                         "Index":  "4"
                     },
        "PIPointExist":  {
                             "Label":  "\"PIPointExist\"",
                             "Visible":  "True",
                             "Index":  "5"
                         },
        "Custom Location":  {
                                "Label":  "\"Custom Location\"",
                                "Visible":  "True",
                                "Index":  "1"
                            }
    }

I've try the following code but it did not work

$json = Get-Content 'C:\column.json' | ConvertFrom-Json
$json = $json | Sort-Object -Property {$_.Index} 
$json | ConvertTo-Json | Out-File 'C:\\column_sorted.json'
  • Why would you like to do that? JSON objects are by [definition unordered](https://stackoverflow.com/a/7214312/503046). Arrays are exception, as those preserve order. – vonPryz Jul 28 '21 at 14:18
  • The JSON contains the list of column that will appear in a report i generate. I want to make the column configurable, so i decide to use JSON to store them. I've created a sub-property to able to make them visible, also decide in which order they will appear in the report and to able to change the display name. – Anastasios Jul 28 '21 at 14:32

2 Answers2

1

One way to do this would be to sort the properties and use Select-Object to reorder the output:

# Return objects based on JSON strings
$jsonObjs = Get-Content 'C:\column.json' | ConvertFrom-Json
# Sorted properties list 
$Properties = ($jsonObjs.psobject.properties | Sort-Object {[int]$_.Value.Index}).Name
# Create new JSON strings with new order
$jsonObjs | Select-Object $Properties | ConvertTo-Json
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27
0

$json¹ is a single object (with just 5 properties).
So you need to sort the properties:

$Data = Get-Content 'C:\column.json' | ConvertFrom-Json
$Properties = [ordered]@{}
$Data.PSObject.Properties |Sort-Object { $_.Value.Index } |ForEach-Object { $Properties[$_.Name] = $_.Value }
[pscustomobject]$Properties | ConvertTo-Json
  1. I would call it $Json as it is no longer a Json string but an object
iRon
  • 20,463
  • 10
  • 53
  • 79