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:
jq
sort_by
Suppose you have a JSON file (data.json) like this:
data.json
[ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35} ]
To sort this array of objects by the age field, use:
age
jq 'sort_by(.age)' data.json
[ {"name": "Bob", "age": 25}, {"name": "Alice", "age": 30}, {"name": "Charlie", "age": 35} ]
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:
to_entries
from_entries
jq 'to_entries | sort_by(.value.age) | from_entries' data.json
To sort in descending order, add the - operator:
-
jq 'sort_by(.age) | reverse' data.json
or
jq 'sort_by(-.age)' data.json
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.