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:
[
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
To sort this array of objects by the age field, use:
jq 'sort_by(.age)' data.json
Output:
[
{"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:
jq 'to_entries | sort_by(.value.age) | from_entries' data.json
Sort in Descending Order
To sort in descending order, add the - operator:
jq 'sort_by(.age) | reverse' data.json
or
jq 'sort_by(-.age)' data.json