How to sort a json file by keys and values of those keys in jq

Solution 1:

Ok with some assistance on the IRC channel I've found an answer.

Basically, it looks like this:

jq \
  '.components.rows|=sort_by(.id)|.components.rows[].properties|=sort_by(.name)' \
  file.json > out.json

Select the right object,
walk into arrays if needed,
then sort_by a single value.

I was trying sort_by(.components.rows.id) which failed.

|= instead of | passes the values along instead of stripping them.

Solution 2:

This doesn't answer the question, but here is another way to sort by attributes/keys:

jq --sort-keys . my_file > sorted_file

-or-

jq -S . my_file > sorted_file