On Linux with `jq` how to sort a dictionary based on one of its field?
Jan 25, 7:06pm

To sort a JSON dictionary (or array of objects) based on one of its fields using jq on Linux, you can use the sort_by function. Here’s how you can do it:

Example: Sort by a Field

Suppose you have a JSON file (data.json) like this:

json
[ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35} ]

To sort this array of objects by the age field, use:

bash
jq 'sort_by(.age)' data.json

Output:

json
[ {"name": "Bob", "age": 25}, {"name": "Alice", "age": 30}, {"name": "Charlie", "age": 35} ]

If Your JSON is a Dictionary (Object)

If your JSON is a dictionary (object) and you want to sort its keys based on a field in the values, you can use to_entries, sort_by, and from_entries:

bash
jq 'to_entries | sort_by(.value.age) | from_entries' data.json

Sort in Descending Order

To sort in descending order, add the - operator:

bash
jq 'sort_by(.age) | reverse' data.json

or

bash
jq 'sort_by(-.age)' data.json

Jan 25, 7:06pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

[ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35} ]
[ {"name": "Bob", "age": 25}, {"name": "Alice", "age": 30}, {"name": "Charlie", "age": 35} ]