Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you sort a JSON object efficiently using JQ

Tags:

json

sorting

key

jq

I've got JSON in the format

{
  "a": {
    "size":3
  },
  "b": {
    "size":2
  },
  "c": {
    "size":1
  }
}

I need to sort it by size, e.g.:

{
  "c": {
    "size": 1
  },
  "b": {
    "size": 2
  },
  "a": {
    "size": 3
  }
}

I have found a way to do it, e.g.:

. as $in | keys_unsorted | map ({"key": ., "size" : $in[.].size}) | sort_by(.size) | map(.key | {(.) : $in[.]}) | add

but this seems quite complex so I'm hoping there's a simpler way that I've overlooked?

like image 908
Nick Peirson Avatar asked Dec 08 '25 20:12

Nick Peirson


1 Answers

You can use to_entries / from_entries, like this:

jq 'to_entries|sort_by(.value.size)|from_entries' file.json

to_entries will transform your input object into a list of key/value pair objects:

[
  {
    "key": "a",
    "value": {
      "size": 3
    }
  },
  ...
  {
    "key": "c",
    "value": {
      "size": 1
    }
  }
]

That allows to apply sort_by(.value.size) to that list and then convert it back to an object using from_entries.

like image 133
hek2mgl Avatar answered Dec 11 '25 15:12

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!