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

JsonSortingJq

Json Problem Overview


We're building a website using the Pentaho CTools library, which has a graphical dashboard editor which writes out JSON-format files for part of the dashboard.

I'd like to apply a transform to these files before check-in to git in order to sort them by key and then by the value of certain keys. The purpose is to make diffs easier, since the editor has a habit of rearranging all of the json fields.

For example, we might have something like this:

{
  "components": {
    "rows": [
      {
        "id": "CHARTS",
        "name": "Charts",
        "parent": "UnIqEiD",
        "properties": [
          {
            "name": "Group",
            "type": "Label",
            "value": "Charts"
          }
        ],
        "type": "Label",
        "typeDesc": "<i>Group</i>"
      },
      {
        "id": "kjalajsdjf",
        "meta_cdwSupport": "true",
        "parent": "CHARTS",
        "properties": [
          {
            "name": "name",
            "type": "Id",
            "value": "Value1"
          },
          {
            "name": "title",
            "type": "String",
            "value": "Value2"
          },
          {
            "name": "listeners",
            "type": "Listeners",
            "value": "[]"
          },
...

We are able to jq --sort-keys (http://stedolan.github.io/jq/) to sort all of the keys, but I'm struggling to find out how to use the sort_by function to then sort certain specific elements by the value of certain keys (so, in the example above, sorting by properties.name for example. Any ideas?

Json Solutions


Solution 1 - Json

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 - Json

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkarlosView Question on Stackoverflow
Solution 1 - JsonkarlosView Answer on Stackoverflow
Solution 2 - JsonThibaud LedentView Answer on Stackoverflow