JQ cheatsheet

A cheatsheet of common jq commands

· 3 min read

I wrote about jq in greater depth here. This is a cheatsheet of commands and function that I’ve found useful for quick reference.

Table of contents

Common usages

Here are some common ways jq is utilized.

Piping from curl

# get the Astronomy Picture of the Day (APOD)
curl -s https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY | jq

(Note that piping to jq with no jq script will just format and colorize the JSON. Nice!)

From a JSON file

Just pass the file path after the jq script.

jq '.name' package.json

In a chain of pipes

You’ll probably want to use the -r (raw) command if you’re using it in a pipeline or saving the output to a variable. -r gets rid of formatting like quotes and spaces for single values. For objects, it outputs valid JSON so it will have quotes.

# this downloads the latest APOD and saves to a file
url="https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"
curl -o apod.png "$(curl -s $url | jq -r '.hdurl')"

Common selectors

Get a named property

echo '{"id": 1, "name": "Cam"}' | jq '.id'``
# 1
echo '{"nested": {"a": {"b": 42}}}' | jq '.nested.a.b'
# 42

Get an array element by index

echo '[0, 1, 1, 2, 3, 5, 8]' | jq '.[3]'
# 3

Get an array element’s property

echo '[{"id": 1, "name": "Mario"}, {"id": 2, "name": "Luigi"}]' | jq '.[1].name'
# Luigi

Slice an array

Slices an array on by index.

echo '["a", "b", "c", "d"]' | jq '.[1:3]'
# ["b", "c"]

Either the first or last index can be omitted to go from the begining or end.

echo '["a", "b", "c", "d"]' | jq '.[1:]'
# ["b", "c", "d"]

Creating a new object

The syntax looks like this: { myPropertyName: .propertyFromJSON }.

echo '{ "a": 1, "b": 2 }' | jq '{ a: .b, b: .a }'
# { "a": 2, "b": 1 }

Useful functions

keys

Gets an object’s keys as an array.

echo '{ "a": 1, "b": 2 }' | jq 'keys'
# [a, b]

length

Gets the length of the array/

echo '[0, 1, 1, 2, 3, 5, 8]' | jq 'length'
# 7

Or the number of top level keys.

echo '{"a": 1, "b": 2}' | jq 'length'
# 2

flatten

Condense a nested array into one.

echo '[1, 2, [3, 4]]' | jq 'flatten'
# [1, 2, 3, 4]

All the above functions used together, just for fun

This gets the total number of dependencies in a package.json file.

jq -r '[(.dependencies, .devDependencies) | keys] | flatten | length' package.json

unique

Gets an array of unique values.

echo '[1, 2, 2, 3]' | jq 'unique'
# [1, 2, 3]

join

Joins the elements of an array using a separator.

echo '{ "firstName": "Cameron", "lastName": "Nokes" }' | jq '[.firstName, .lastName] | join(" ")'
# Cameron Nokes

We create an array of the properties we want joined, pipe to join which is passed a space as the separator.