JSON wrangling with jq
Help 8 / 10
Summarize data

Pipes and Filters

Before I can use sort to sort the labels from my GitHub API request, I need to explain how pipes and filters work in jq.

jq is a filter in the UNIX command line sense. You pipe (|) a JSON document to it, and it filters it and outputs it to standard out. I could easily use this feature to chain together jq invocations like this:

echo '{"title":"JQ Select"}' | \
   jq '.title' | \
   jq 'length'

This is a wordy, though simple, way to determine the length of a string in a JSON document. You can use this same idea to combine various jq built-in functions with the features I’ve shown so far. But there is an easier way, though. You can use pipes inside of jq and conceptually they work just like shell pipes:

echo '{"title": "JQ Select"}' | \
   jq '.title | length'

Here are some more examples:

  • .title | length will return the length of the title
  • .number | tostring will return the issue number as a string
  • .[] | .key will return the values of key key in the array (this is equivalent to this .[].key)

This means that sorting my labels array is simple. I can just change .labels to .labels | sort:

jq '{ title: .title, number: .number, labels: .labels | sort }' issue.json

And if you want just a label count that is easy as well:

jq '{ title: .title, number: .number, labels: .labels | length }' issue.json
Loading...