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:
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:
bashjq 'sort_by(.age)' data.json
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:
bashjq 'to_entries | sort_by(.value.age) | from_entries' data.json
To sort in descending order, add the - operator:
bashjq 'sort_by(.age) | reverse' data.json
or
bashjq 'sort_by(-.age)' data.json
Vibe can make mistakes. Check answers. Learn more