简体   繁体   中英

Using jq to sort keys then values in json

Anyone knows how to use jq to sort keys and their array values in json?

For example:

Before sort:

{ 
   z:["c","b","a"],
   y:["e", "d", "f"],
   x:["g", "i", "h"]
}

After sort:

{
   x:["h", "i", "j"]
   y:["d", "e", "f"],
   z:["a","b","c"]
}

I am trying to use

jq --sort-keys 

but it only sorts the keys, but not including their values.

Thanks!

If you are willing to rely on the --sort-keys command-line option to sort the keys, then you can ensure all arrays are sorted by writing:

walk(if type=="array" then sort else . end)

If you want the object keys to be sorted internally (ie before the final output is generated), then you could augment the above by using the following filter:

walk(if type=="array" then sort
     elif type == "object" then to_entries | sort | from_entries
     else . end)

Alternatives

If for some reason you wish not to use walk , then you can roll your own solution using some combination of sort (for JSON arrays) and to_entries|sort|from_entries (for JSON objects).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM