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:
.nameoutputs the value of keyname..user.address.cityfollows nested objects..["first name"]or."first name"accesses keys that are not simple identifiers.- A missing key gives
null, not an error:.nopeoutputsnull.
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 AnnRemember
- 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.