How do you handle missing keys, nulls and defaults in `jq`?
IntermediateConceptfind, xargs, jq and yq
Answer
jq -r '.spec.replicas // 1' # default when null or missing
jq '.items[]?.name' # ? suppresses errors on non-iterable
jq -r '.tags // [] | .[]' # iterate safely even if null
jq 'has("status")' # key exists?
jq -e '.data.token' f.json >/dev/null || die "token missing"
Without -e, jq exits 0 even when the result is null, so token=$(jq -r .token f) silently gives the string null. Check for it: [[ $token != null && -n $token ]].
More on find, xargs, jq and yq
What are the most useful `find` predicates for operations work?BeginnerWhat is the difference between `-exec cmd {} \;`, `-exec cmd {} +` and `-delete`?IntermediateHow does `find` evaluate `-o` (OR) and why do you need parentheses?AdvancedWhat does `xargs` do, and which flags matter?IntermediateWhy is `find | xargs rm` dangerous and what is the safe form?IntermediateWhat is `jq` and what are the filters you use every day?Beginner