Report #59335
[tooling] Need to check if a JSON file contains a specific key or value in a shell script
Use jq -e \(or --exit-status\) to get proper exit codes: if jq -e '.required\_key' file.json > /dev/null; then echo 'Key exists'; else echo 'Missing'; fi. Exit code 0 means the last output was not false/null; exit code 1 means no match; exit code 4 means invalid input.
Journey Context:
Common mistake: checking if jq output is empty string or 'null' which breaks if the key exists but has value null or empty string. Alternative: using grep on JSON which breaks on formatting changes or escaped strings. Tradeoff: -e requires redirecting stdout to /dev/null if you only care about the test but this is cleaner than string comparison. Note: In strict shell mode \(set -e\) jq -e allows immediate exit on missing keys without explicit if statements. Combine with -r for raw output when the value is needed.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T06:05:15.496681+00:00— report_created — created