jq is a command-line program that can transform JSON in several ways. Takes a JSON object as input and produces an output.

cat db.json | jq '<filter>'

Table of Contents

Parameters

  • -c: By default, jq pretty-prints JSON output. Using this option will result in a more compact output.

Selecting fields

You can select fields by typing a dot (.) and the field name.

# db.json
{"name":"john", "id":3}
$ cat db.json | jq '.name'
"john"

You can also select several fields.

$ cat db.json | jq '.name, .id'

Arrays

You can select one or several items of an array by appending [] to the field name. If you add an index inside the brackets, it will output that item (arrays are zero-based, first item has index 0). If you do not add any number, it will return all items. [0:5] will return an array with items from index 0 to 4.

# db.json
{"Items":[{"name":"john"},{"name":"tom"}]}
$ cat db.json | jq '.Items[0]'
{"name":"john"}

Pipes

Pipes works as in UNIX/Linux: parses the output of one filter as input to another filter. For example:

# db.json
{"Items":[{"id":1, "model":"Samsung S10"}, {"id":2, "model":"Apple iPhone 10"}]
$ cat db.json | jq '.Items[] | .id, .model'
1
"Samsung S10"
2
"Apple iPhone 10"

Built-in functions

  • map(<filter>): it will run <filter> for each element of an array.
    # db.json
    {"Items":[{"id":1, "model":"Samsung S10"}, {"id":2, "model":"Apple iPhone 10"}]
    
    $ cat db.json | jq '.Items | map(.model)'
    "Samsung S10","Apple iPhone 10"
    
    • This is almost the same as: jq '.Items[] | .model' but map returns an array.
  • has("<key>"): returns if the object has the given key.
    # db.json
    {"Items":[{"id":1, "phone":"+01234567"}, {"id":2}]
    
    $ cat db.json | jq 'Items[] | .id, has("phone")'
    1
    true
    2
    false
    
  • tonumber: parses its input as a number.
    # db.json
    {"id":"1"}
    
    $ cat db.json | jq '.id | tonumber'
    1
    
  • tostring: parses its input as a string.
  • add: takes an array and outputs the elements of the array together. If the elements are numbers, it will make a sum, if they are strings, it will concatenate them in one string.
    # db.json
    {"values": [1,2,3]}
    
    $ cat db.json | jq '.values | add'
    6
    
  • sort and sort_by(<filter>): sort sorts its input (must be an array). sort_by(<filter>) sorts by comparing the result of <filter>.
    # db.json
    [{"id": 3, "name":"john"}{"id":1, "name":"tom"}]
    
    $ cat db.json | jq 'sort_by(.id)'
    [{"id":1, "name":"tom"},{"id":3, "name":"john"}]
    

More info

I have shown you only the basics about jq because this awesome program has a lot of features. You can learn more on its man page (man jq).

Test with this online terminal: