Tips on jq
jq
is a fast, streaming JSON parser accessible from the command line, capable of reading and transforming well-formatted JSON. Below are some references of actions you can do with jq
:
- Exploring JSON data of any size. For large files,
jq
is often the fastest way to view the data. Usejq -C
to output with ANSI color codes andless -R
to properly display them.curl -s https://api.github.com/events \ | jq -C | less -R
- Isolating specific elements within repeating structures. Use
jq -r
to output raw results..
refers to the top level of the JSON object.[]
addresses each object in an array individually..FIELD_SELECTOR
selects a specific field.curl -s https://api.github.com/events \ | jq -r '.[].type' \ | sort | uniq
- Selecting results based on conditions.
|
pipes results to the next step, similar to Unix pipes.select(BOOLEAN_EXPRESSION)
applies a boolean expression to each element and retains only those that evaluate totrue
.curl -s https://api.github.com/events \ | jq '.[] | select(.type == "PushEvent") | .payload.commits[].message'
- Mapping and formatting results.
| [.FIELD_SELECTOR1, .FIELD_SELECTOR2]
creates an array with the results of each selector.| @tsv
formats the output as a tab-separated table (other formats include@csv
,@json
,@uri
,@base64
).curl -s https://api.github.com/events \ | jq -r '.[] | select(.type == "PushEvent") | .payload.commits[] | [.author.email, .sha, .message] | @tsv'
- Performing string interpolation.
curl -s https://api.github.com/events \ | jq -r '.[] | "\(.actor.display_login) - \(.type) on repo:\(.repo.name) at date:\(.created_at)" '