Sort descending by multiple keys in jq Sort descending by multiple keys in jq json json

Sort descending by multiple keys in jq


In jq, arrays sort by the sorting of the elements they contain, in order. That is:

$ jq -n '[1, 2] < [1, 3], [1, 2] < [2, 1]'truetrue

The sort_by filter sorts an array, taking an expression as argument that will be evaluated for each member of the array. For example, if you wanted to sort a list of words by length:

$ jq -n '["prop", "leo", "column", "blast"] | sort_by(length)'[  "leo",  "prop",  "blast",  "column"]

If the expression given to sort_by as argument returns more than one value, the return values will be implicitly wrapped in an array, which will be subject to the array sorting rules referred to above. For example, if you wanted to sort a list of words by length, and then alphabetically:

$ jq -n '["pro", "leo", "column", "ablast"] | sort_by(length, .)'[  "leo",  "pro",  "ablast",  "column"]

Knowing this, and taking into account that the values in your example are numeric, you can just do the following:

$ jq 'sort_by(-.prop1, .prop2)'