$ command-helper

jq

Querying and transforming JSON in the terminal: fields, arrays, filters, output formats.

Requires Google sign-in

Basics

Pretty-print JSON
jq . <file>.json
Get a field
jq '.name' <file>.json
Nested field without quotes in output
jq -r '.user.email' <file>.json
Keys of an object
jq 'keys' <file>.json
Compact one-line output
jq -c . <file>.json

Arrays

Field of every element
jq -r '.[].name' <file>.json
Array length
jq 'length' <file>.json
First element
jq '.[0]' <file>.json
Filter elements by a condition
jq '.[] | select(.status == "active")' <file>.json
Build new objects from elements
jq '[.[] | {id, name: .user.name}]' <file>.json
Sort by a field
jq 'sort_by(.createdAt) | reverse' <file>.json

Advanced

Count by a fieldadvanced
jq 'group_by(.status) | map({status: .[0].status, count: length})' <file>.json
Export to CSVadvanced
jq -r '.[] | [.id, .name, .email] | @csv' <file>.json
Change a field and saveadvanced
jq '.version = "1.2.3"' package.json > tmp.json && mv tmp.json package.json
Pass a shell variable into jqadvanced
jq --arg name "$NAME" '.[] | select(.name == $name)' <file>.json
Find a key anywhere in the documentadvanced
jq '.. | .<json_key>? // empty' <file>.json
Parse JSON logs line by lineadvanced
tail -f app.log | jq -R 'fromjson? | select(.level == "error")'