Given this JSON data in the file data.json
:
[
{ "id": 1, "entityType": "cat" },
{ "id": 2, "entityType": "dog" },
{ "id": 3, "entityType": "bird" },
{ "id": 4, "entityType": "cat" }
]
How would return an array sorted by some non-alphabetic arbitrary order (e.g dogs, birds and then cats)?
I’ve tried various permutations along the lines of:
jq --argjson order '["dog", "bird", "cat"]' '. | sort_by( index($order[], .entityType) )' data.json
but without any joy.
2
Answers
It’s easier (and faster) to use an object for the order:
But if you insist:
If you want to keep your
order
argument an array, sort by turning it into an implicit boolean array of matches. Note thatfalse
will be ordered beforetrue
, so use!=
to "mismatch" the items.Alternatively, provide the order as single arguments using the
--args
option and the$ARGS.positional
array: