Skip to content

Instantly share code, notes, and snippets.

@JacobAMason
Last active September 17, 2026 17:03
Show Gist options
  • Select an option

  • Save JacobAMason/e936444873ecc8ea6e0f43987929598e to your computer and use it in GitHub Desktop.

Select an option

Save JacobAMason/e936444873ecc8ea6e0f43987929598e to your computer and use it in GitHub Desktop.
jqhl -- JSON output highlighting
#!/usr/bin/env bash
# jqhl - spotlight JSON paths without filtering them away.
#
# Reads JSON on stdin, pretty-prints ALL of it, and emphasizes the paths you
# name. Nothing is removed, so a demo audience sees that the payload really is
# big -- you just point at the part that matters.
#
# aws ec2 describe-instances | jqhl '.Reservations[].Instances[].State.Name'
#
# Depends on: bash (3.2+, so macOS /bin/bash works) and jq (1.6+). Nothing else.
set -euo pipefail
usage() {
cat <<'EOF'
usage: jqhl [-m] [--mode spotlight|highlight] [--collapse] [--legend]
[-C] [--list-colors] [--demo] [paths ...]
paths jq-ish paths, optionally 'color:' prefixed
-m, --multicolor give each path its own palette color (default: all yellow)
--mode MODE spotlight dims the rest; highlight inverts the match
and leaves the rest normal
--collapse render match-free subtrees as {...} / [...]
--legend print a color key above the JSON
--demo tour the path syntax against a built-in fixture
(also a smoke test: reports N/N examples matched)
-C, --force-color emit color even when stdout is not a terminal
(e.g. piping into `less -R`)
--list-colors show available color names
Path syntax: .Key .* [] [*] [0] ."odd key"
A matched path also emphasizes everything beneath it. When two paths both
match a line, the more specific (longer) one wins.
EOF
}
# bash 3.2 compatible (macOS /bin/bash): no associative arrays, no ${x,,}.
COLOR_NAMES="yellow cyan green magenta blue red white"
PALETTE=(yellow cyan green magenta blue red)
DEFAULT_COLOR=yellow
color_code() {
case $1 in
yellow) echo 93 ;; cyan) echo 96 ;; green) echo 92 ;;
blue) echo 94 ;; red) echo 91 ;; magenta) echo 95 ;;
white) echo 97 ;;
*) return 1 ;;
esac
}
lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }
# Should we emit color? Shared by the renderer and --demo.
want_color() {
[ -z "${NO_COLOR:-}" ] && { $force_color || [ -t 1 ]; }
}
DEMO_FIXTURE='{
"Reservations": [
{
"ReservationId": "r-0a1b2c3d",
"OwnerId": "123456789012",
"Instances": [
{
"InstanceId": "i-0abc123",
"InstanceType": "m5.large",
"State": {"Code": 16, "Name": "running"},
"Monitoring": {"State": "disabled"},
"Tags": [{"Key": "Name", "Value": "api-1"}, {"Key": "env", "Value": "prod"}]
},
{
"InstanceId": "i-0def456",
"InstanceType": "c6g.xlarge",
"State": {"Code": 80, "Name": "stopped"},
"Monitoring": {"State": "enabled"}
}
]
}
]
}'
# Tour the path syntax against DEMO_FIXTURE. Every example also asserts that
# it matched something, so this doubles as a smoke test on a new machine.
demo() {
demo_total=0 demo_missed=0
demo_color_flag=""
want_color && demo_color_flag="-C"
echo '# fixture: an abridged "aws ec2 describe-instances" response'
printf '%s\n' "$DEMO_FIXTURE"
demo_case "the entire top-level key" \
'.Reservations'
demo_case "a nested scalar" \
'.Reservations[0].OwnerId'
demo_case "a whole subtree" \
'.Reservations[].Instances[].State'
demo_case "every element of an array" \
'.Reservations[].Instances[].Tags[]'
demo_case "just the first element" \
'.Reservations[].Instances[].Tags[0]'
demo_case "every value in an object, keys unknown" \
'.Reservations[].Instances[].State.*'
demo_case "one field across every instance" \
'.Reservations[].Instances[].State.Name'
demo_case "a field inside a list inside a list" \
'.Reservations[].Instances[].Tags[].Value'
demo_case "one specific instance" \
'.Reservations[0].Instances[1].InstanceId'
demo_case "any Name one level down, whatever the parent" \
'.Reservations[].Instances[].*.Name'
demo_case "two paths, two colors" -m \
'.Reservations[].Instances[].InstanceId' \
'.Reservations[].Instances[].State'
demo_case "subtree washed, one field picked out of it" \
'cyan:.Reservations[].Instances[].State' \
'yellow:.Reservations[].Instances[].State.Name'
demo_case "abridge everything that does not match" --collapse \
'.Reservations[].Instances[].State.Name'
demo_case "color key for a multi-path demo" --legend -m \
'.Reservations[].Instances[].InstanceId' \
'.Reservations[].Instances[].Tags'
printf '\n# %s/%s examples matched\n' \
"$((demo_total - demo_missed))" "$demo_total"
[ "$demo_missed" -eq 0 ] || return 1
}
demo_case() {
demo_desc=$1; shift
demo_total=$((demo_total + 1))
printf '\n# %s\n$ jqhl %s\n' "$demo_desc" "$*"
# Capture so both a "no path matched" warning AND a hard failure can be
# counted. Checking only the warning let a jq usage error report as a pass.
# Re-invoke under the RUNNING interpreter, not the shebang's: otherwise
# `/bin/bash jqhl --demo` would smoke-test some other bash on PATH.
if demo_out=$(printf '%s\n' "$DEMO_FIXTURE" \
| "${BASH:-bash}" "$0" ${demo_color_flag:+$demo_color_flag} "$@" 2>&1); then
demo_status=0
else
demo_status=$?
fi
demo_bad=""
case $demo_out in
*"no path matched"*) demo_bad="no path matched" ;;
esac
[ "$demo_status" -eq 0 ] || demo_bad="exited $demo_status"
if [ -n "$demo_bad" ]; then
demo_missed=$((demo_missed + 1))
printf ' !! %s\n' "$demo_bad"
fi
printf '%s\n' "$demo_out" | grep -v 'jqhl: no path matched' || true
}
mode=spotlight collapse=false legend=false multicolor=false force_color=false
run_demo=false
paths=()
while (($#)); do
case $1 in
-h|--help) usage; exit 0 ;;
-m|--multicolor) multicolor=true ;;
--mode) mode=${2:?--mode needs a value}; shift ;;
--mode=*) mode=${1#*=} ;;
--collapse) collapse=true ;;
--legend) legend=true ;;
-C|--force-color) force_color=true ;;
--demo) run_demo=true ;;
--list-colors)
for c in $COLOR_NAMES; do
tags=""
[ "$c" = "$DEFAULT_COLOR" ] && tags="default"
i=0
for p in "${PALETTE[@]}"; do
i=$((i + 1))
if [ "$p" = "$c" ]; then
[ -n "$tags" ] && tags="$tags, "
tags="${tags}--multicolor slot $i"
fi
done
suffix=""
[ -n "$tags" ] && suffix=" ($tags)"
printf '\033[1;%sm%s\033[0m%s\n' "$(color_code "$c")" "$c" "$suffix"
done
exit 0 ;;
--) shift; paths+=("$@"); break ;;
-*) echo "jqhl: unknown flag $1" >&2; usage >&2; exit 2 ;;
*) paths+=("$1") ;;
esac
shift
done
case $mode in spotlight|highlight) ;; *)
echo "jqhl: --mode must be spotlight or highlight" >&2; exit 2 ;;
esac
# --demo needs no stdin, so handle it before we try to read any.
if $run_demo; then
demo
exit $?
fi
color=false
if want_color; then
color=true
fi
# Split 'cyan:.a.b' into a color and a path, defaulting per --multicolor.
# NB: the per-path color is spec_color, NOT color -- $color is the boolean
# "should we emit escapes at all", and reusing the name silently broke every
# invocation that named a path.
# bash 3.2 + set -u: "${arr[@]}" on an empty array errors, so guard the loop.
specs='[]'
n=0
if [ ${#paths[@]} -gt 0 ]; then
for spec in "${paths[@]}"; do
if $multicolor; then
fallback=${PALETTE[$((n % ${#PALETTE[@]}))]}
else
fallback=$DEFAULT_COLOR
fi
spec_color=$fallback raw=$spec
if [[ $spec =~ ^([A-Za-z]+):[.\[$] ]]; then
name=$(lower "${BASH_REMATCH[1]}")
if ! color_code "$name" >/dev/null; then
echo "jqhl: unknown color '$name'; try: $COLOR_NAMES" >&2
exit 2
fi
spec_color=$name raw=${spec#*:}
fi
# Reject a malformed path rather than silently highlighting nothing -- a
# typo that looks like "no interesting fields" is the worst demo outcome.
if [[ ! $raw =~ ^((\.([A-Za-z0-9_*-]+|\"[^\"]*\"))|\[(\*|[0-9]*)\])+$ ]]; then
echo "jqhl: malformed path '$raw' (expected e.g. .a.b, .a[].b, .\"odd key\")" >&2
exit 2
fi
specs=$(jq -c --arg c "$spec_color" --arg p "$raw" \
--argjson d "$(color_code "$spec_color")" \
'. + [{c:$c, code:$d, raw:$p}]' <<<"$specs")
n=$((n + 1))
done
fi
if $legend && $color && [[ $specs != '[]' ]]; then
jq -r --arg mode "$mode" '
.[] | (if $mode == "highlight" then "7;" else "1;" end) as $sgr
| "\u001b[\($sgr)\(.code)m \(.c) \u001b[0m \(.raw)"' <<<"$specs"
echo
fi
jq -r --argjson specs "$specs" \
--argjson color "$color" \
--argjson collapse "$collapse" \
--arg mode "$mode" '
def pad($n): if $n == 0 then "" else " " * $n end;
# ".a[].b" -> [{t:"key",v:"a"},{t:"idx",v:null},{t:"key",v:"b"}]
def parse_pattern:
[ match("\\.(?:\"(?<q>[^\"]*)\"|(?<k>[A-Za-z0-9_*-]+))|\\[(?<i>\\*|[0-9]*)\\]"; "g")
| (.captures | map({(.name): .string}) | add)
| if .q != null then {t:"key", v:.q}
elif .k != null then {t:"key", v:(if .k == "*" then null else .k end)}
elif .i != null then {t:"idx", v:(if .i == "" or .i == "*" then null
else (.i | tonumber) end)}
else empty end ];
def tok_ok($tok; $part):
if $tok.t == "key"
then ($part | type) == "string" and ($tok.v == null or $tok.v == $part)
else ($part | type) == "number" and ($tok.v == null or $tok.v == $part)
end;
# $path IS the pattern node, or sits beneath it.
def matched($path; $toks):
($path | length) >= ($toks | length)
and ([range(0; $toks | length)]
| all(. as $i | tok_ok($toks[$i]; $path[$i])));
# A match could still turn up strictly below $path.
def may_contain($path; $toks):
($toks | length) > ($path | length)
and ([range(0; $path | length)]
| all(. as $i | tok_ok($toks[$i]; $path[$i])));
($specs | map({code, toks: (.raw | parse_pattern)})) as $pats
# Most specific match wins; null when nothing matches.
| def best($path):
[ $pats[] | select(matched($path; .toks)) ]
| if length == 0 then null
else (sort_by(.toks | length) | last) end;
def render($v; $depth; $prefix; $suffix; $path):
pad($depth) as $pad
| ($v | type) as $ty
| if ($ty == "object" or $ty == "array") and ($v | length) > 0 then
( if $collapse
and ([ $pats[] | select(matched($path; .toks)
or may_contain($path; .toks)) ] | length) == 0
then [{p: $path,
t: ($pad + $prefix
+ (if $ty == "object" then "{...}" else "[...]" end)
+ $suffix)}]
elif $ty == "object" then
($v | keys_unsorted) as $ks
| [{p: $path, t: ($pad + $prefix + "{")}]
+ ( [ range(0; $ks | length) as $i
| render($v[$ks[$i]]; $depth + 1; ($ks[$i] | tojson) + ": ";
(if $i < ($ks | length) - 1 then "," else "" end);
$path + [$ks[$i]]) ] | add // [] )
+ [{p: $path, t: ($pad + "}" + $suffix)}]
else
[{p: $path, t: ($pad + $prefix + "[")}]
+ ( [ range(0; $v | length) as $i
| render($v[$i]; $depth + 1; "";
(if $i < ($v | length) - 1 then "," else "" end);
$path + [$i]) ] | add // [] )
+ [{p: $path, t: ($pad + "]" + $suffix)}]
end )
else [{p: $path, t: ($pad + $prefix + ($v | tojson) + $suffix)}]
end;
render(.; 0; ""; ""; [])
| [ .[] | . + {hit: best(.p)} ] as $lines
# First line is a sentinel carrying the match count, stripped by bash.
| "\u0001\([ $lines[] | select(.hit != null) ] | length)",
( $lines[]
| . as {t: $t, hit: $hit}
| if ($color | not) or ($pats | length) == 0 then $t
else
($t | sub("^(?<s> *)"; "")) as $body
| ($t | capture("^(?<s> *)").s) as $indent
| if $hit != null then
(if $mode == "highlight" then "7;" else "1;" end) as $sgr
| "\($indent)\u001b[\($sgr)\($hit.code)m\($body)\u001b[0m"
elif $mode == "spotlight" then
"\($indent)\u001b[2;37m\($body)\u001b[0m"
else $t end
end )
' | {
# Peel the sentinel, stream the rest, then warn about a path that hit nothing.
IFS= read -r sentinel || exit
hits=${sentinel#$'\001'}
cat
if [ ${#paths[@]} -gt 0 ] && [ "$hits" = 0 ]; then
echo "jqhl: no path matched" >&2
fi
}
@JacobAMason

Copy link
Copy Markdown
Author

This is a simple, vibe-coded script for highlighting outputs instead of truncating. Makes live demos a bit easier to follow without resorting to filtering out unrelated fields. Useful in that most folks are used to full outputs and there is a mental disconnect between the filtered version and what they are used to seeing.

Screenshot 2026-09-17 at 11 58 36 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment