Simple jq command examples


jq is a Linux-based command-line JSON processor. In other words it’s a command which can parse and extract data from JSON content.

Let’s assume we have the following simple JSON content:

{
  "name": "John Smith",
  "age": 43,
  "email": "john.smith@example.com"
}

We would like to extract the “John Smith” text from JSON content. How can we achieve that? Here comes the jq command to our help as shown by the following example:

echo '{"name": "John Smith", "age": 43, "email": "john.smith@example.com"}' | jq -r '.name'

The output of this command will be as follows:

John Smith

As the next example, we try to parse the following JSON content that is a bit more complex:

{
    "_embedded": {
        "environments": [
            {
                "uuid": "762b3c1f-52e7-48e3-8017-1bfa2f71d897",
                "name": "production",
                "displayName": "Production",
                "production": true,
                "createdAt": "2022-07-22T23:37:47+00:00"
            },
            {
                "uuid": "b67b0e48-b7fd-fd02-550c-a01d3d0a490f",
                "name": "test",
                "displayName": "Test",
                "production": false,
                "createdAt": "2022-07-22T23:37:47+00:00"
            }
        ]
    }
}

This time we want to retrieve a whole JSON object (in this example an environment object) by one of its properties (in this example the name property).

To apply the jq command on this JSON content, we first save this JSON content as a JSON file and call it file.json.

We put the jg command in the following script and call it script.sh:

#!/bin/bash

# Define the name of the environment to retrieve
name="production"

# Use jq to retrieve the environment object with the matching name
jq -r --arg name "$name" '._embedded.environments[] | select(.name == $name)' -

Then we read the JSON content from the file.json file and pipe it to the script above:

cat file.json | ./script.sh

This will result in the following output:

{
  "uuid": "762b3c1f-52e7-48e3-8017-1bfa2f71d897",
  "name": "production",
  "displayName": "Production",
  "production": true,
  "createdAt": "2022-07-22T23:37:47+00:00"
}