Skip to main content
JSON processing:

jq cheat sheet

Summary

This cheat sheet provides a concise reference for jq, covering syntax, functions, and practical examples to parse, filter, and transform JSON data from the command line. It includes basic operations, advanced transformations, and real-world use cases.

Introduction #

jq is a command-line JSON processor. It allows you to parse, filter, transform, and output JSON (JavaScript Object Notation) data using simple expressions.

Basic Usage #

Read a JSON file #

jq '.' file.json           # Pretty-print entire file
jq -r '.' file.json        # Raw output (no quotes/formatting)
jq -c '.' file.json        # Compact (single-line) output

Pipe JSON from another command #

curl https://api.example.com/data | jq '.results[] | .name'

Syntax Reference #

OperatorDescriptionExample
.Identity (returns input unchanged)jq '.' file.json
.keyAccess a fieldjq '.user' file.json
.[]Iterate over array/object valuesjq '.items[]' file.json
.[0]First array elementjq '.[0]' file.json
.[2:5]Array slice (indices 2, 3, 4)jq '.items[1:3]' file.json
,Combine filters into one streamjq '.user, .profile' file.json
\|Pipe output to another filterjq '.items[] \| .name'
select(...)Filter by conditionjq '.[] \| select(.price > 10)'
map(...)Transform array elementsjq 'map(. * 2)' file.json
//Default value if null/emptyjq '.name // "Anonymous"'
as $varVariable assignmentjq '.items[] as $item \| $item.name'
..Recursive descent (nested search)jq '.. \| .name? // empty'
?Suppress errors (optional key)jq '.user.missing?' file.json

Functions #

FunctionDescriptionExample
keysList keys of an objectjq 'keys' file.json
lengthLength of array/object/stringjq '.items \| length'
flattenFlatten nested arraysjq 'flatten' file.json
uniqueDeduplicate arrayjq 'unique' file.json
join(str)Join array into stringjq 'join(", ")' file.json
has(key)Check if key existsjq 'select(has("email"))'
del(key)Remove a fieldjq 'del(.user.password)'
addSum array of numbersjq 'map(.price) \| add'

Advanced Operations #

String Interpolation #

jq '"User: \(.name), Age: \(.age)"' data.json

Construct JSON Objects/Arrays #

jq '{name: .user, id: .id}' data.json                # New object
jq '[.items[] \| {name, price}]' data.json           # Array of objects

Math Operations #

jq '.prices[] \| . * 1.1'                            # 10% increase
jq 'map(.price) \| add'                              # Sum all prices

Conditionals (if-then-else) #

jq '.users[] \| if .age >= 18 then "Adult" else "Minor" end'

Format Conversion #

jq -r '.items[] \| [.name, .price] \| @csv'          # CSV output
jq -r '.items[] \| [.name, .price] \| @tsv'          # TSV output
jq -r '.command \| @sh'                              # Shell-safe string

Arguments & Variables #

Pass external values to jq:

jq --arg key "value" '.[$key]' data.json             # String
jq --argjson items '[1, 2, 3]' '$items[]'            # Raw JSON

Use Cases #

Extract API Data #

curl https://api.example.com/users | jq '.[] \| {name, email}'

Filter Logs #

cat log.json | jq 'select(.level == "error") \| .message'

Transform JSON Structure #

jq '{user: .name, metadata: {age: .age, id: .id}}' data.json

FAQ's #

Most common questions and brief, easy-to-understand answers on the topic:

How do you use jq with a file?

You run jq followed by the filter and the file name, like this: jq '.' input.json.

What is the purpose of the flatten function in jq?

The flatten function recursively flattens nested arrays into a single-level array.

Can you use jq in a pipe?

Yes, you can pipe JSON input into jq using standard input, for example: curl ... | jq '.'.

What does the keys function do in jq?

The keys function returns the list of keys in an object as an array.

Is jq only for JSON?

Yes, jq is specifically designed to parse, filter, and transform JSON data.

Further readings #

Sources and recommended, further resources on the topic:

Author

Jonas Jared Jacek • J15k

Jonas Jared Jacek (J15k)

Jonas works as project manager, web designer, and web developer since 2001. On top of that, he is a Linux system administrator with a broad interest in things related to programming, architecture, and design. See: https://www.j15k.com/

License

jq cheat sheet by Jonas Jared Jacek is licensed under CC BY-SA 4.0.

This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:

<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/jq-cheat-sheet">jq cheat sheet</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>

For more information see the Ditig legal page.

All Topics

Random Quote

“Cool URIs don't change.”

Tim Berners-Lee English computer scientist, inventor of the World Wide WebW3C Style Guide for online hypertext, - IT quotes