Skip to content
System

Read a JSON file with jq on Linux without messing around with grep

Avatar illustré de Julien Macé 3 min read
Manchot Linux examinant une structure de données JSON
jq permet de lire une structure JSON sans dépendre de sa présentation sur une ligne ou sur dix.

An API response arrives in JSON, you look for a value, and then you end up with grep and cut. This can work as long as the file maintains exactly the same formatting. As soon as a key moves into a nested object, a list appears, or the response becomes an HTML page after an HTTP error, the script sometimes reads the wrong data.

jq reads the JSON structure instead of searching for a string of characters. It is the right tool for extracting a field, filtering a list, and failing a script when the expected data is missing.

Linux penguin examining a JSON data structure
jq allows reading a JSON structure without depending on its presentation on one line or ten.

Check jq and the file before the request

On Debian or Ubuntu, install the package with sudo apt update && sudo apt install jq. Fedora, RHEL, and their derivatives generally use sudo dnf install jq. Start by checking the command and the document that your script will read.

jq --version
jq empty config.json

jq empty does not display the document. It checks its syntax and returns an error if the file is truncated or invalid. Perform this check before a loop, a deployment, or a configuration change. An HTTP 502 response saved in a .json file remains HTML, not JSON.

Extract a field and filter a list

For this test file, the service has a name and a port, while each node has its own state.

{
  "service": {"name": "api", "port": 8080},
  "nodes": [
    {"name": "web-1", "enabled": true},
    {"name": "worker-1", "enabled": false}
  ]
}

The -r option removes the quotes around a string. It is useful when the value needs to be used by another command.

jq -r '.service.name' config.json
jq -r '.nodes[] | select(.enabled == true) | .name' config.json

The first command outputs api. The second traverses nodes, retains the objects where enabled is true, and then displays only their name. The official jq manual describes this traversal with .[], filters, and select().

Fail the script if the value is missing

An administration script should not continue with an empty variable. The -e option gives an actionable return code: zero if the last result is present and different from false or null, one if the value is false or null, four if no result is produced.

#!/usr/bin/env bash
set -euo pipefail

file="config.json"
jq empty "$file"

if port=$(jq -er '.service.port? // empty' "$file"); then
  printf 'Configured port: %sn' "$port"
else
  printf 'Port missing or invalid JSONn' >&2
  exit 1
fi

Keep jq filters in quotes under Bash. The shell will then not attempt to interpret $, [], or | before jq. If the field may contain a secret, also avoid displaying it with printf in CI logs.

Why grep eventually breaks

grep searches for text. It does not distinguish between a port key in service and another key of the same name in a neighboring object. The order of fields, spaces, line breaks, and escaped characters can also change without modifying the JSON data.

Keep grep for a text log or a quick search in a file that you control. For an API response, a configuration file, or an export, use jq. If you first need to fetch the API, the guide curl on Linux helps to control the HTTP code and headers before passing the response to jq.

Keep jq in its place in automation

For a configuration file or a normal-sized API response, jq remains the most readable choice. On a very large document, avoid --slurp: this option loads the entire stream into an array. The --stream mode exists to handle large streams, but it imposes a different filter and deserves testing on a copy.

I would also keep a copy before modifying JSON in place. For a versioned configuration, first have jq write to a new file, compare with diff -u, then replace the original if the result matches the expected output. The same principle avoids surprises with sed on Linux.

Before letting a value guide another command, validate the JSON, extract the field using -e, and check its output. It is shorter than a grep | cut pipeline, and especially the script stops when the structure is no longer what was expected.

Share Facebook X WhatsApp LinkedIn Pinterest Reddit Email