jq Session 04: Conditions

Decision making in jq. This session covers conditional logic, null handling, and error recovery.

Pre-Session State

  • Can construct objects and arrays

  • Can output CSV/TSV

  • Understand string interpolation

Setup

cat > /tmp/jq-mixed.json << 'EOF'
[
  {"name": "kvm-01", "cpu": 85, "status": "running", "error": null},
  {"name": "kvm-02", "cpu": 45, "status": "running"},
  {"name": "vault-01", "cpu": 92, "status": "warning", "error": "high load"},
  {"name": "db-01", "status": "stopped", "error": "disk full"}
]
EOF

Lesson 1: If/Then/Else

Concept: if COND then EXPR else EXPR end for branching.

Exercise 1.1: Basic condition

cat /tmp/jq-mixed.json | jq '.[] | if .cpu > 80 then "HIGH" else "OK" end'

Output: "HIGH" for cpu > 80, "OK" otherwise.

Exercise 1.2: With field access

cat /tmp/jq-mixed.json | jq '.[] | {name: .name, alert: (if .cpu > 80 then true else false end)}'

Output: Objects with computed alert field.

Exercise 1.3: Nested conditions

cat /tmp/jq-mixed.json | jq '.[] |
  if .status == "stopped" then "CRITICAL"
  elif .cpu > 90 then "WARNING"
  elif .cpu > 70 then "ELEVATED"
  else "NORMAL" end'

Lesson 2: Alternative Operator

Concept: // provides a default when left side is null or false.

Exercise 2.1: Default for missing field

cat /tmp/jq-mixed.json | jq '.[] | .cpu // 0'

Output: CPU value or 0 if missing (db-01 has no cpu field).

Exercise 2.2: Default for null

cat /tmp/jq-mixed.json | jq '.[] | {name: .name, error: (.error // "none")}'

Output: "none" when error is null or missing.

Exercise 2.3: Chain alternatives

cat /tmp/jq-mixed.json | jq '.[] | .error // .status // "unknown"'

Output: First non-null value in chain.

Lesson 3: Null Handling

Concept: Understand null propagation and testing.

Exercise 3.1: Check for null

cat /tmp/jq-mixed.json | jq '.[] | select(.error != null) | .name'

Output: Names of hosts with errors (including explicit null).

Exercise 3.2: Filter out nulls

cat /tmp/jq-mixed.json | jq '[.[] | .cpu] | map(select(. != null))'

Output: Array of CPU values, nulls removed.

Exercise 3.3: Null-safe access

cat /tmp/jq-mixed.json | jq '.[] | .cpu? // 0'

Output: ? suppresses errors from missing fields.

Lesson 4: Try/Catch

Concept: try EXPR catch FALLBACK handles errors gracefully.

Exercise 4.1: Safe type conversion

echo '{"value": "not a number"}' | jq 'try (.value | tonumber) catch 0'

Output: 0 (conversion failed, caught).

Exercise 4.2: Safe array access

echo '{"items": [1,2,3]}' | jq 'try .items[10] catch "out of bounds"'

Output: null (jq returns null for out-of-bounds, no error).

Summary: What You Learned

Concept Syntax Example

If/else

if C then A else B end

if .x > 10 then "high" else "low" end

Elif

elif

if A then X elif B then Y else Z end

Alternative

//

.error // "none" default value

Null test

!= null

select(.x != null)

Safe access

.field?

.cpu? no error if missing

Try/catch

try E catch F

try .x catch 0

Exercises to Complete

  1. [ ] Add severity field: CRITICAL if stopped, WARNING if cpu > 90, else OK

  2. [ ] Create report with error message or "healthy" for each host

  3. [ ] Filter to only hosts with CPU > 50 (handle missing cpu)

  4. [ ] Build alert list: only hosts where error is not null and not "none"

Next Session

Session 05: Advanced - sort, group_by, reduce, aggregation.

Session Log

Timestamp Notes

Start

<Record when you started>

End

<Record when you finished>