Working with JSON in bash using `jq`

jq is a powerful tool that lets you read, filter, and write JSON in bash

Cameron Nokes
Jul 16, 2018 · 5 min read
Image for post
Image for post
curl -s "http://api.icndb.com/jokes/random" \
| python -m json.tool \
| grep '\"joke\"' \
| cut -d ':' -f 2 \
| sed 's/"/\"/g'
curl -s "http://api.icndb.com/jokes/random" | jq '.value.joke'

Why not just use node.js when you need to deal with JSON?

Install jq

Basics of jq

{ "foo": 123, "bar": 456 }
echo '{ "foo": 123, "bar": 456 }' | jq '.foo'
echo '{ "Version Number": "1.2.3" }' | jq '."Version Number"'
echo '[1,2,3]' | jq '.[]'
echo '[ {"id": 1}, {"id": 2} ]' | jq '.[].id'
echo '{ "a": 1, "b": 2 }' | jq '.[]'
echo '["foo", "bar"]' | jq '.[1]'
echo '["foo", "bar"]' | jq '.[]' | touch
echo '{ "a": 1, "b": 2 }' | jq 'keys | .[]'
echo '[1,2,3]' | jq 'length'
jq -r '[(.dependencies, .devDependencies) | keys] | flatten | length' package.json

Let’s use it for real now

See numbered comments below for an explanation.


Cameron Nokes

Javascript and front-end development how-tos

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store