DEV Community

cheatsheetmaker
cheatsheetmaker

Posted on

JQ Cheat Sheet

JQ is a lightweight and flexible command-line JSON processor. This is a cheatsheet of commands and function that I’ve found useful for quick reference. You can get full JQ Cheat Sheet Here .

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
Enter fullscreen mode Exit fullscreen mode

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')"
Enter fullscreen mode Exit fullscreen mode

Common selectors

Get a named property

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

Get an array element by index

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

Enter fullscreen mode Exit fullscreen mode

Get an array element’s property

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

Slice an array

Slices an array on by index.

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

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"]
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
epsi profile image
E.R. Nurwijayadi

Good article. Thank you for posting.

JQ could solve JSON, such as parsing response from telegram bot.

To help more beginner, I have made a working example of JQ in bash to solve unique challenge.

🕷 epsi.bitbucket.io/lambda/2021/02/1...

First the JSON source example.

JSON Source

And the JQ in BASH to solve unique challenge.

JQ in BASH

I hope this could help other who seeks for other case example.

🙏🏽

Thank you for posting the cheat sheet.