jq: Sorting JSON objects

jq: Sorting JSON objects

Last updated:
Table of Contents

Sort objects by attribute value

Use jq 'sort_by(.my_attribute):

Example: sort objects by attribute attr_2

  • Input:

    [
      {
        "attr_1": "foo",
        "attr_2": 1
      },
      {
        "attr_1": "baz",
        "attr_2": 3
      },
      {
        "attr_1": "bar",
        "attr_2": 2
      }
    ]
    
  • Command

    $ cat objects.json | jq 'sort_by(.attr_2)'

  • Output

    [
      {
        "attr_1": "foo",
        "attr_2": 1
      },
      {
        "attr_1": "bar",
        "attr_2": 2
      },
      {
        "attr_1": "baz",
        "attr_2": 3
      }
    ]
    

Sort objects by attribute value, reverse

To sort objects in descending order instead use: jq 'sort_by(.my_attribute) | reverse'

Example: sort objects by attribute attr_2, in descending order

  • Input:

    [
      {
        "attr_1": "foo",
        "attr_2": 1
      },
      {
        "attr_1": "baz",
        "attr_2": 3
      },
      {
        "attr_1": "bar",
        "attr_2": 2
      }
    ]
    
  • Command

    $ cat objects.json | jq 'sort_by(.attr_2) | reverse'

  • Output

    [
      {
        "attr_1": "baz",
        "attr_2": 3
      },
      {
        "attr_1": "bar",
        "attr_2": 2
      },
      {
        "attr_1": "foo",
        "attr_2": 1
      }
    ]