#Sort JSON by keys

9 messages · Page 1 of 1 (latest)

safe shell
#

Looking for a way to sort a json string by keys but ignore arrays since the order could be significant, and also do not merge duplicate keys together. ConvertFrom-Json has this problem that it merges duplicate keys, so this seems kind of hard to do.

marble estuary
#

its not a problem, its how they should be handled

safe shell
#

This is a helper function for a library that uses mustache. I want it to sort but not otherwise change as that can hide problems with the mustache or my parameters.

marble estuary
#

yeah im just alluding to the fact that you're really going to struggle finding a solution since it would be handling the json differently than the standard

high flume
#

Have you tried pwsh 7+ ? It seems to work there.

For a second I thought it broke but the formatter is misleading.
but data worked for both

$rows = @( 
   [pscustomobject]@{ Z = 'fred' }
   [pscustomobject]@{ a = 10; }
   [pscustomobject]@{ a = 99 } 
   [pscustomobject]@{ b = 'jen' }
)

# $rows | ConvertTo-Json

$data1 = $rows | ConvertTo-Json | ConvertFrom-Json
$data2 = $rows | ConvertTo-Json | ConvertFrom-Json -AsHashtable

$data  | fl * -Force # without -Force, the properties don't all render
$data2 | ft
marble estuary
#

oh you just mean it doesn't merge

#

this is the problem though

$json = @"
{
  "a": "one",
  "b": "two",
  "c": "three",
  "b": "four"
}
"@
$json | ConvertFrom-Json

# a   c     b
# -   -     -
# one three four

$json | ConvertFrom-Json -AsHashtable

# Name                           Value
# ----                           -----
# a                              one
# c                              three
# b                              four