Using jq to extract a single field from nested JSON logs

Extracting a Single Field from Nested JSON Logs with jq

Running a homelab or a tiny self‑hosted service usually means dealing with JSON‑encoded logs. Whether it’s systemd‑journal, docker logs, or a custom app, the output is often a tidy JSON object per line. The catch? Those objects are usually nested, and if you only care about one value—like the HTTP status code or a user ID—you’ll waste a lot of time sifting through the whole file. That’s where jq steps in.

Below I’ll walk through what JSON logs look like, how to install and test jq, the basics of extracting a field, dealing with deep nesting, and a few real‑world tricks. I’ll keep the tone casual, as if we’re chatting over coffee in the Linux Café.


Why JSON Logs?

JSON is lightweight, human‑readable, and maps cleanly to the data structures most languages use. For logs it means:

Feature Benefit
Key‑value pairs Easy to reference by name
Arrays Group related items (e.g., request headers)
Nested objects Preserve hierarchy without line‑breaks
Schema‑free Add new fields without breaking parsers

Because of this, many modern services emit logs in JSON. With systemd‑journal you can even query logs directly and pipe them straight into jq.


1. Installing jq

It’s in every distro’s repo. For Debian/Ubuntu:

sudo apt update
sudo apt install -y jq

Fedora/RHEL:

sudo dnf install -y jq

Arch:

sudo pacman -S jq

Check it works:

jq --version
# jq-1.6

That’s the current stable release as of 2026.


2. A Sample Log Entry

Let’s start with a realistic HTTP‑server log. One JSON object per line:

{
  "timestamp": "2026-11-28T14:32:07Z",
  "request": {
    "method": "GET",
    "path": "/api/users",
    "headers": {
      "host": "example.com",
      "user-agent": "curl/7.88.1",
      "accept": "*/*"
    }
  },
  "response": {
    "status": 200,
    "body": {
      "users": [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"}
      ]
    }
  },
  "client_ip": "192.0.2.123"
}

Want just the status code (200)? The field lives under response.status. Let’s pull it out.


3. Basic Extraction

The most common filter is:

jq -r '.response.status'
  • -r outputs raw text, so numbers aren’t quoted.
  • .response.status walks the object tree.

Try it on a file:

cat access.log | jq -r '.response.status'

Output:

200

For multi‑line logs, jq prints one status per line.


4. Working with Arrays

If the value is inside an array, use []:

jq -r '.access.ips[]'

Result:

192.0.2.123
198.51.100.45
203.0.113.7

Want a comma‑separated list instead of one per line? Wrap it in @csv:

jq -r '.access.ips | @csv'

Output:

"192.0.2.123","198.51.100.45","203.0.113.7"

5. Deeply Nested Fields

Chaining filters is the trick:

jq -r '.response.body.users[] | .id'

If a key might be missing, add ? and a default:

jq -r '.response.body.users[]?.id // "unknown"'

The ? after [] stops jq from throwing when users is absent or empty.


6. Filtering with select()

Often you want to filter first, then extract. For example, only show non‑200 statuses:

jq -r 'select(.response.status != 200) | .response.status'

Or filter by client IP:

jq -r 'select(.client_ip == "192.0.2.123") | .response.status'

Combine conditions:

jq -r 'select(.client_ip == "192.0.2.123" and .response.status != 200) | .response.status'

7. Using jq with journalctl

If you’re on a systemd machine, query logs directly:

journalctl -u myservice.service -o json | \
  jq -r '.MESSAGE | fromjson | .response.status'

Explanation:

  1. -o json makes journalctl emit each entry as JSON.
  2. The MESSAGE field is still a JSON string.
  3. fromjson turns that string into a JSON object.
  4. Finally, .response.status extracts the status.

For real‑time monitoring:

journalctl -f -u myservice.service -o json | \
  jq -r '.MESSAGE | fromjson | .response.status'

8. Quick Use Cases

Scenario jq Command Why It Helps
Count 404s `journalctl -o json jq -r ‘.MESSAGE
Unique client IPs `jq -r ‘.client_ip’ access.log sort -u`
Error messages `jq -r ‘select(.response.status >= 500) .response.body.error’`
CSV report `jq -r ‘[.timestamp, .client_ip, .response.status] @csv’ access.log`

9. Common Pitfalls

Symptom Fix
jq: error: Cannot iterate over null (null) Use ? or // empty: jq -r '.response.body.users[]?.id // empty'
jq: error: Cannot index string with string “status” Input might be a string; parse it first: `jq -r ‘fromjson?
jq: error: Cannot index array with string “response” Top‑level is an array; iterate first: `jq -r ‘.[]
Slow on huge files Consider --stream for deep extraction, but usually not needed for homelab logs.

10. Security Bits

Logs can hold secrets. Remember:

  • Permissions – Keep them readable only by trusted users (chmod 640 /var/log/access.log).

  • Output – Don’t pipe jq output into commands that echo it back to the console. Redirect to a file with strict perms.

  • Injection – If you build filters from user input, use --arg:

    jq --arg ip "192.0.2.123" 'select(.client_ip == $ip) | .response.status' access.log
    
  • Audit – Use auditd to track who reads logs.


11. Custom Functions

You can define reusable snippets:

jq '
  def status_text:
    if .response.status == 200 then "OK"
    elif .response.status == 404 then "Not Found"
    else "Other" end;

  status_text
'

Then pipe the output elsewhere or use it in a script.


12. Shell Wrapper Example

Wrap jq in a function for readability:

extract_status() {
  jq -r '.response.status' "$1"
}

extract_status access.log | grep -c 500

13. Real‑World: Monitoring a Raspberry Pi API

You run a tiny REST API on a Pi, logs live in /var/log/api.log. Want to capture 5xx errors in real time and store timestamps:

journalctl -u api.service -o json | \
  jq -r '.MESSAGE | fromjson | select(.response.status >= 500) | .timestamp' >> /var/log/api_errors.log

Then:

tail -f /var/log/api_errors.log
grep -c . /var/log/api_errors.log

14. When to Skip jq

  • Very simple logs – awk or grep can be quicker.
  • Need to join with other data – Use csvkit or Python’s pandas.
  • Massive streams – Consider a log aggregator like Loki or Fluentd that can query JSON fields natively.

15. Bottom Line

jq is a lightweight, versatile tool that fits right into the Linux command‑line toolbox. Use dot notation for single fields, [] for arrays, and select() to filter before you extract. Combine it with journalctl, grep, or shell scripts for real‑time monitoring or batch analysis. Just watch out for missing keys, permissions, and output handling.

Happy logging, and enjoy that extra cup of coffee!

See also