Bash & Shell Scripting (50 Qs)•Part 3: Advanced Text Processing & Production Internals (Senior / Lead)
Working with JSON in Bash: Best practices using `jq` vs fragile regex parsing.
senior LevelMost AskedCode Examplebash-shellAdvanced Text Processing
In Simple Words:
Never parse JSON with grep, sed, or awk — multiline strings, escaped quotes, and nested arrays break regex immediately. Always use jq:
bash
JSON_DATA='{"user":{"id":101,"name":"Sarah","roles":["admin","editor"]}}'
# Extract single field
NAME=$(jq -r '.user.name' <<< "$JSON_DATA")
# Filter and iterate over arrays
for role in $(jq -r '.user.roles[]' <<< "$JSON_DATA"); do
echo "User Role: $role"
done
# Transform and produce new JSON
NEW_PAYLOAD=$(jq --arg ip "192.168.1.1" '.user + {ip: $ip}' <<< "$JSON_DATA")