22
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 .
Here are some common ways jq is utilized.
# 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!)
Just pass the file path after the jq script.
jq '.name' package.json
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')"
echo '{"id": 1, "name": "Cam"}' | jq '.id'``
# 1
echo '{"nested": {"a": {"b": 42}}}' | jq '.nested.a.b'
# 42
echo '[0, 1, 1, 2, 3, 5, 8]' | jq '.[3]'
# 3
echo '[{"id": 1, "name": "Mario"}, {"id": 2, "name": "Luigi"}]' | jq '.[1].name'
# Luigi
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 }
22