Skip to content

Command-line JSON processor cheatsheet

Basic usage

Read JSON input and format it

curl https://json-api-url | jq '.' 

or read input from the file

jq '.' file.json

Accessing JSON properties

jq '.url'

Nested objects

jq '.committer.login'

To get multiple keys, separate them with comma

jq '.committer.login,.committer.type,.committer.url'

Wrap all retrieved properties in new object

jq '{login:.committer.login,type:.committer.type,url:.committer.url}'

Formatting options

  • -c --compact-output - do not pretty-print the output
  • -r --raw-output - if the filter output is string, do not format as JSON string (no quotes)

Arrays

Iterate over JSON array

jq '.[]'

Access element by index

jq '.[0]'

Display given element

jq '.[].element_name'


Slicing

Get elements 4-6

echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[3:6]'

Get first 5 elements

echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[:5]'

Get two last elements

echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[-2:]'

Get 3rd from the back

echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[-3]'

Functions

Array length

jq 'length'

Keys

jq 'keys'

Minimum

jq '[.[].price] | min'

Maximum

jq '[.[].price] | max'

Select elements

jq 'select(.Verified == true)'

Multiple conditions

jq 'select((.status_code == 200) and (.content_type == "application/json"))'

Multiple filters

Pass output of the one filter to another, build an object from those fields

jq '.[] | {message: .commit.message, name: .commit.committer.name}'

Build an array of the objects from the filter

jq '[.[] | {message: .commit.message, name: .commit.committer.name}]'

Converting between JSON and JSONL

JSONL to JSON

jq -s '.' input.jsonl > output.json

JSON to JSONL

jq -c '.[]' input.json > output.jsonl

References