A simple module that will reorder a json keys in alphabetical order
Install-Module SortJson -Force
- Format-JsonOrder : Primary caller
- ConvertTo-OrderObject : Called when using Format-JsonOrder but can be used separately
- Set-ObjectPropertyOrder : Called when using ConvertTo-OrderObject but can be used separately
- Json : Required: [String or Object] The JSON text to sort.
- PropertyStartList : Optional: [Array] The list of properties to put at the start of the json object.
- PropertyEndList : Optional: [Array] The list of properties to put at the end of the json object.
- OnlyListedProperties : Optional: [switch] Only list the properties that are in the PropertyStartList and PropertyEndList.
- SortAlphabetically : Optional: [switch] Sort the properties alphabetically.
- IgnoreCaseSensitivity : Optional: [switch] Ignore case sensitive ordering. Case Sensitivity is enabled by default
- Recursive : Optional: [switch] Sort the properties that are arrays or objects.
WARNING: Specifying lists of properties that do not exist and the -OnlyListedProperties parameter combined will return an empty json
Sort-Json
parameter | alias |
---|---|
-PropertyStartList | StartList, First |
-PropertyEndList | EndList, Last |
-OnlyListedProperties | OnlyListed |
-SortAlphabetically | Ascending |
-IgnoreCaseSensitivity | CaseInSensitive |
-Recursive | Recurse |
$json = @"
{"displayName":"A test of json","policyType":"BuiltIn","mode":"Indexed","description":"A test to see if the json get ordered","metadata":{"version":"1.1.0","category":"Ordering"},"parameters":{"effect":{"type":"String","metadata":"@{displayName=Ordering; description=Order or not order that is the question}","allowedValues":"Yes No","defaultValue":"Yes"}},"policyRule":{"if":{"allOf":" "},"then":{"effect":"[parameters('order')]"}},"scopetag":["order","json","default","unorder"]}
"@
#Original JSON...
$json | ConvertFrom-Json | ConvertTo-Json -Depth 100
#Sorted JSON using pipeline...
$json | Format-JsonOrder -SortAlphabetically -Recursive
$json = @"
{"displayName":"A test of json","policyType":"BuiltIn","mode":"Indexed","description":"A test to see if the json get ordered","metadata":{"version":"1.1.0","category":"Ordering"},"parameters":{"effect":{"type":"String","metadata":"@{displayName=Ordering; description=Order or not order that is the question}","allowedValues":"Yes No","defaultValue":"Yes"}},"policyRule":{"if":{"allOf":" "},"then":{"effect":"[parameters('order')]"}},"scopetag":["order","json","default","unorder"]}
"@
#Sorted JSON using Alias...
$json | Sort-Json -First @('policyType','displayName') -Last @('policyRule') -Ascending -Recurse