Select Page

Considering cat file.json be any JSON input from a file or API response, etc.

Read the whole file with JSON aware viewer

jq '.' file.json

# OR
cat file.json | jq '.'

The rest of the write-up assumes the file being read with cat format before piping in the jq commands.

Plain text compact JSON over pretty-printed JSON? Use -c option.

jq -c ‘.’ file.json

Get top-level keys

jq '. | keys'
jq '.innerObject | keys'

Get top-level objects count

jq '. | length'

Get data for top-level objects

jq '. | {object, ...}'

Get data from inner object

jq '.inner | {object, ...}'

Get data from inner array-object

jq '.inner[] | {object, ...}'

Get data as plain text

jq '.inner[] | join("" "")'

JSON to CSV using jq

jq '.inner[] | join("","")'

Filter by attribute value using a select query

jq '.inner[] | select(.first == ""Sam"")'
jq '.inner[] | select((.first == ""Sam"") and (.second == ""Tiger""))'
jq '.inner[] | select(.first | contain( ""Sa""))'
jq '.inner[] | select(.somearray | length > 0)'

Avoid nulls

jq '.randomkey | select(. != null)'

Changing data values in memory

jq '. |= . + { ""newObject"": ""newValue"" }'
jq '.randomkey |= .+ [ ""newMember"" ]'

Delete keys/objects from JSON

jq 'del(.randomkey)' file.json

Write updated JSON back to the disk

Writing the in-memory data back to disk can be achieved using indirection (>) to the same file.

This will overwrite the content with the new desired content.

Good idea to preview the changes first, though.