jq is a lightweight command line JSON processor that is very easy to use. Sometimes it is helpful to see your data sorted by a particular field value. Luckily jq makes this easy to do. Here are some sample JSON records we will be working with in this post:

{"first_name":"Savannah","last_name":"Williams"}
{"first_name":"Aria","last_name":"Acevedo"}
{"first_name":"Emma","last_name":"Puckett"}
{"first_name":"Claire","last_name":"Mathis"}
{"first_name":"Ryder","last_name":"Wong"}

Sorting JSON by value with jq can easily be done by using the sort_by() function. The main trick with using the sort_by() function is that your JSON input must be in an array. There are different ways to do this in jq (if your data is not already like this), including using the -s or --slurp option. The --slurp option will read all JSON input into a JSON array. From this point the data can be sorted by value. You can use the .[] syntax to return all elements of the array.

Sorting by a Single Value Example

#!/bin/bash

$ cat sample.json | jq -s -c 'sort_by(.first_name) | .[]'

{"first_name":"Aaliyah","last_name":"Simpson"}
{"first_name":"Aaliyah","last_name":"Cervantes"}
{"first_name":"Aaliyah","last_name":"Emerson"}
{"first_name":"Aaliyah","last_name":"Fletcher"}
{"first_name":"Aaliyah","last_name":"Hopkins"}
{"first_name":"Aaliyah","last_name":"Schroeder"}
{"first_name":"Aaron","last_name":"Landry"}
...

Sorting by Multiple Values Example

#!/bin/bash

$ cat sample.json | jq -s -c 'sort_by(.first_name, .last_name) | .[]'

{"first_name":"Aaliyah","last_name":"Cervantes"}
{"first_name":"Aaliyah","last_name":"Emerson"}
{"first_name":"Aaliyah","last_name":"Fletcher"}
{"first_name":"Aaliyah","last_name":"Hopkins"}
{"first_name":"Aaliyah","last_name":"Schroeder"}
{"first_name":"Aaliyah","last_name":"Simpson"}
{"first_name":"Aaron","last_name":"Bradley"}

jq is a great library and I highly recommend reading through the official documentation found here.

Leave a Reply

Sorting JSON by Value with JQ (Command Line JSON Processor)