Processing JSON with jq
Formatting
Pretty print:
jq . file.json
Minify:
jq -c . file.json
Extracting values
Extract a property by dot path:
jq .the.dot.path.to.property file.json
Extract as raw text (no quotes):
jq -r .the.path file.json
Arrays
Get the first element:
jq '.[0]' file.json
Get specific properties from each object in an array:
jq '.[] | {id, name}' file.json
Wrap the results back into an array:
jq '[.[] | {id, name}]' file.json
Filtering
Select objects matching a condition:
jq '.[] | select(.status == "active")' file.json
Exclude by condition:
jq '.[] | select(.type != "NS" and .type != "SOA")' file.json
Nested extraction
Extract a nested field and reshape:
jq '[.items[] | {
id: .id,
name: .name,
email: .creator.email
}]' file.json
Combining values
Join array values into a string:
jq '.values | map(.name) | join(",")' file.json
Conditionally extract from different shapes:
jq '.[] | if .records then (.records | map(.value) | join(",")) else .alias end' file.json
Output formats
Output as CSV:
jq -r '.[] | [.id, .name, .status] | @csv' file.json
Output as TSV:
jq -r '.[] | [.id, .name, .status] | @tsv' file.json
Piping from other commands
Process output from another command directly:
some-command | jq -r '.items[] | [.id, .name] | @csv'