Loading...

About the jq cheat sheet

jq is a small functional language rather than a flag-driven tool, and treating it as the latter is why it feels impenetrable at first. Everything is a filter that takes input and produces output, and the pipe composes them exactly as a shell pipe does.

Four constructs cover most real use. The identity and field access filters navigate structure, the array iterator flattens a list into a stream, select filters that stream by a condition, and map applies a filter to every element of an array. Almost every kubectl-processing one-liner you will write is a combination of those.

The distinction that trips people up is a stream of values versus an array of values. Iterating produces separate outputs; wrapping that in brackets collects them back into one array. Getting this wrong is why output sometimes appears as several documents when you wanted one, and it is the source of most confusing jq errors.

Frequently asked questions

How do I get plain strings without quotes?

Use raw output mode, which prints string results without JSON quoting. This is what you want when piping into another command or building a shell loop. Without it, every value arrives quoted and the next command receives literal quote characters as part of the argument.

How do I filter a kubectl list by a field?

Iterate the items array, then select on the condition you care about. The pattern is to iterate, select, then extract the fields you want. Remember that kubectl returns a List object, so the items live under a top-level items key rather than at the root.

Why does my filter return null?

The path does not exist in the input, and jq returns null rather than failing. Check the actual structure first by piping to keys at the level you are querying. Optional access with a question mark suppresses errors on missing paths, which is useful when processing heterogeneous documents where some lack a field.

How do I output CSV or TSV?

Build an array of the values you want per row, then pass it through the CSV or TSV filter, combined with raw output so the result is not JSON-quoted. This is the cleanest way to turn API output into something a spreadsheet or a shell loop can consume.

Should I use jq or kubectl's built-in output options?

Use custom columns or jsonpath for simple field extraction — no extra dependency and adequate for most listing. Reach for jq when you need real filtering, aggregation or reshaping, which jsonpath handles poorly. For scripts that must run anywhere, kubectl's built-in options avoid assuming jq is installed.