jq: Slice and Shape JSON
Get fluent in jq — pull fields out of JSON, filter and reshape arrays, build new objects, aggregate with group_by and reduce, and turn messy JSON into clean CSV, TSV or plain text from the shell.
JSON is everywhere — API responses, config files, log lines, cloud output — and jq is the tool that lets you reach into it from the command line without writing a script. It is a small language built around one idea: a filter that takes JSON in and gives JSON out, with pipes between filters just like the shell. We start from the identity filter and build up real fluency one small thing at a time: reading fields, iterating arrays, selecting and mapping, constructing new objects, aggregating with add, group_by and reduce, and finally formatting the result as raw text, CSV or TSV. Everything runs against a couple of small sample files you can keep on hand, so each idea lands on its own and you can try it immediately.
What you'll build
- Read fields out of objects and arrays with jq paths
- Iterate, filter with select, and reshape with map
- Construct new objects and pull out keys
- Aggregate with add, group_by, sort_by and reduce
- Pass shell values in and slurp a stream of inputs
- Emit raw text, CSV and TSV for the rest of the pipeline
Contents
- Check your jq
- A file to play with
- The identity filter
- Reach into the array
- Pull out a field
- Go a level deeper
- Slice a range
- Iterate the array
- Pipe filters together
- Iterate a field that isn't always there
- Make it optional
- Keep only what matches
- Filter, then narrow
- Transform every element
- Build a slimmer object
- Rename as you build
- List an object's keys
- Measure with length
- Check for a field
- Supply a default
- Turn an object into pairs
- Drop the quotes with -r
- Build a sentence
- Emit CSV
- Or tab-separated
- A second file with numbers
- Sum with add
- Order by a field
- Drop duplicates
- Group and total
- Find the extreme
- Fold it yourself with reduce
- Pass in a value with --arg
- Pass a number with --argjson
- Read the environment
- Write a stream of JSON
- Slurp the stream into an array
- Search everywhere with ..
- List the paths
- Delete a field
- Compact output with -c
- Put it all together