JQ: Introduction & Simple Examples

JQ is a powerful and lightweight command line JSON processor. It is a tool no web developer should be without. There are almost endless possibilities with jq, but here are a few basic examples:

echo '{"jules":27,"leo":30,"bella":19,"ella":36}' | jq '.jules'
27

echo '{"jules":27,"leo":30,"bella":19,"ella":36}' | jq '{females: [.jules,.bella,.ella]}'
{
  "females": [
    27,
    19,
    36
  ]
}

echo '{"jules":27,"leo":30,"bella":19,"ella":36}' | jq '.[]'
27
30
19
36

echo '{"jules":27,"leo":30,"bella":19,"ella":36}' | jq 'keys'
[
  "bella",
  "ella",
  "jules",
  "leo"
]

There are some useful bash aliases you can setup to make dealing with JSON a bit more manageable in the command line

# takes whatever JSON we have in our clipboad, minifies it and copies it back to our clipboard
function minify() {
    pbpaste | jq -c '.' $@ | pbcopy
}

# takes our minified JSON from our clipboard and expands it and copies it back to our clipboard
function copyJson() {
    pbpaste | jq '.' $@ | pbcopy
}

# outputs the json we have in our clipboard out to our terminal in pretty format
# also if the json is invalid tells us where the error is
function validate() {
    pbpaste | jq '.' $@
}

Read more about JQ here Check out our part two deep dive into JQ.

Instagram Post