snippetbashModeratepending
jq recipes -- command-line JSON processing
Viewed 0 times
jqJSONfilterselectmapcommand linepipe
terminallinuxmacos
Problem
Need to extract, filter, and transform JSON data from APIs or log files on the command line. Parsing JSON with grep/sed is fragile and error-prone.
Solution
Use jq for structured JSON processing. Pipe curl output or read files directly.
Code Snippets
jq recipes for JSON processing
# Extract field
echo '{"name": "Alice", "age": 30}' | jq '.name'
# "Alice"
# Extract from array
curl -s https://api.github.com/users/octocat/repos | \
jq '.[].name'
# Filter array
jq '[.[] | select(.age > 25)]' users.json
# Transform objects
jq '.[] | {name, email}' users.json
# Conditional
jq '.[] | if .active then .name else empty end' users.json
# Create new structure
jq '{total: length, names: [.[].name]}' users.json
# Raw strings (no quotes)
jq -r '.[] | "\(.name): \(.email)"' users.json
# Process NDJSON (newline-delimited)
cat logs.jsonl | jq -c 'select(.level == "error")'
# Combine with curl
curl -s https://api.example.com/data | jq '.results[] | {id, title}'Revisions (0)
No revisions yet.