Pretty-printing and field access

jq · Essentials · 6 min

Pulling one value out of a big JSON response is the most common thing you will ever do with jq.

jq reads JSON from standard input (or files) and runs a filter on it. The simplest filter is ., the identity: it outputs its input unchanged, pretty-printed and coloured. That alone makes jq worth installing: curl ... | jq .

To pick fields:

  • .name outputs the value of key name.
  • .user.address.city follows nested objects.
  • .["first name"] or ."first name" accesses keys that are not simple identifiers.
  • A missing key gives null, not an error: .nope outputs null.

Strings are output as JSON, with quotes. Add -r (raw output) to print the plain text, which is what you want when assigning to a shell variable: name=$(jq -r .name user.json).

If the input is not an object, field access is an error: .name on an array fails with "Cannot index array with name". Adding ? suppresses the error: .name?.

Always put the filter in single quotes in the shell. jq programs are full of characters the shell would otherwise interpret, such as |, [, $ and ".

Example

echo '{"user":{"name":"Ann","address":{"city":"Oslo"}},"first name":"A"}' > u.json
jq . u.json                    # pretty-printed and coloured
jq .user.name u.json           # "Ann"
jq -r .user.name u.json        # Ann
jq '.user.address.city' u.json # "Oslo"
jq '."first name"' u.json      # "A"
jq .user.phone u.json          # null
name=$(jq -r .user.name u.json); echo "hi $name"   # hi Ann

Remember

  • jq . pretty-prints; .a.b extracts nested fields
  • -r prints strings raw, without JSON quotes
  • Single-quote jq programs in the shell

Watch out for

  • Forgetting -r when capturing a value into a shell variable, ending up with literal quotes.

Check yourself

  1. What does `echo '{"a":{"b":1}}' | jq .a.c` print?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: jqlang.org/tutorial/

Builds on

Nothing: this is a foundation.

Unlocks

Pretty-printing and field access · jq · Topolearn