jq Tutorial: Slice JSON Like a Pro From the Terminal
Quick answer: jq is a small command-line tool that reads JSON, filters it, reshapes it, and prints the result, all without writing a script.
It is not jQuery, the old browser library; the two share two letters and nothing else.
You call an API and get back a wall of JSON. Somewhere in it is the one number you need, maybe total sales for Karachi, but the response is five hundred lines long. A browser formatter or a quick script both break your flow. jq sits in the middle: one command, one filter, and the answer is on your screen.
It reads JSON from a file or a pipe, applies a short expression, and prints only what you asked for. The rest of this post uses one real file, five orders from a small shop, and shows the filter, the error that stops the sum, and the one-line fix.
What I would check before using it
My first check is what jq actually is. It is a filter language and a command-line program in one, built only for JSON. You give it an expression like .[] | select(.city == "Karachi") and it walks the data for you. If your data is YAML, CSV, or XML, jq is the wrong tool. The Postman Explained: Testing APIs Before the Frontend Exists post covers the point where you first see that JSON.
My second check is the learning curve. The basics take an afternoon: dot access, pipes, select, and map cover most daily questions. The deeper parts, like group_by and reduce, take longer, and the error messages are terse. That is a fair trade, but keep long filters in a file with the -f flag, since a long one-liner is hard to review.
My third check is where the JSON comes from. jq shines on API responses piped from curl and log files full of JSON lines. It cannot edit data in place, because it prints a new document and never touches the file. The FastAPI Explained: Python APIs at Full Speed post shows the other side of the same job, a full API that serves orders instead of just reading them.
My verdict, as judgement: use jq whenever you need a quick answer from JSON at the terminal. Reach for Python when the job needs loops or retries, or writing results back to a file. The recommendation flips if your data is not JSON, or if the query has grown so long that nobody on the team can read it at a glance.
Five orders, one broken sum, and a fix
Five orders belong to one small shop in Karachi. Sana in Karachi, Rs 9,800; Daniyal in Lahore, Rs 13,400; Mahnoor in Islamabad, Rs 11,200; Hamza in Karachi, Rs 6,750; Ayesha in Karachi, Rs 4,200. One detail matters: Hamza's total was typed as the string "6750", not the number 6750, the kind of slip a real order file contains.
Every command below runs against orders.json.
[
{ "id": 101, "customer": "Sana", "city": "Karachi", "items": ["kurta", "dupatta"], "total": 9800 },
{ "id": 102, "customer": "Daniyal", "city": "Lahore", "items": ["sneakers"], "total": 13400 },
{ "id": 103, "customer": "Mahnoor", "city": "Islamabad", "items": ["handbag", "wallet"], "total": 11200 },
{ "id": 104, "customer": "Hamza", "city": "Karachi", "items": ["jacket"], "total": "6750" },
{ "id": 105, "customer": "Ayesha", "city": "Karachi", "items": ["shawl"], "total": 4200 }
]
First, count the orders and list the Karachi customers.
$ jq 'length' orders.json
5
$ jq -r '.[] | select(.city == "Karachi") | .customer' orders.json
Sana
Hamza
Ayesha
$ jq -r '.[] | "\(.customer) - \(.city) - Rs \(.total)"' orders.json
Sana - Karachi - Rs 9800
Daniyal - Lahore - Rs 13400
Mahnoor - Islamabad - Rs 11200
Hamza - Karachi - Rs 6750
Ayesha - Karachi - Rs 4200
Now add up the totals. This is where the day goes wrong: one total is a string, and jq refuses to add a number and a string together.
$ jq '[.[] | .total] | add' orders.json
jq: error (at orders.json:7): number (34400) and string ("6750") cannot be added
The 34400 is the running total of the first three orders, and then it hits Hamza's "6750" and gives up. The fix is tonumber, which converts each total to a number before adding. The real grand total is Rs 45,350.
$ jq '[.[] | .total | tonumber] | add' orders.json
45350
The same fix powers sales per city: sort_by(.city) comes first, because group_by needs sorted input.
$ jq 'sort_by(.city) | group_by(.city) | map({city: .[0].city, orders: length, sales: (map(.total | tonumber) | add)})' orders.json
[
{ "city": "Islamabad", "orders": 1, "sales": 11200 },
{ "city": "Karachi", "orders": 3, "sales": 20750 },
{ "city": "Lahore", "orders": 1, "sales": 13400 }
]
Karachi leads with three orders and Rs 20,750. The same orders appear in the Elysia Bun Tutorial: Build a Real Orders API for Shops post, where they travel through an API instead of a file, and the Koa Tutorial: Build a Node.js Orders API From Scratch post shows the Node side of serving them.
Common mistakes and how to fix them
- First, mixing strings and numbers in a sum. The symptom is the error shown above, "number (34400) and string ("6750") cannot be added", with exit code 5. The fix is to normalise each value first with
tonumber, as the demo did, or fix the source data so totals are always numbers. - Second, reading a key that does not exist. The symptom is a silent null:
jq '.[0].discount'printsnullbecause no order has adiscountfield. The fix is a default with the//operator, sojq '.[] | .discount // 0'prints0for every order. - Third, indexing an array with a key. The symptom is the error "Cannot index array with string "total"" when you run
jq '.total'on the whole file. The fix is to iterate first:jq '.[] | .total'reads each order, then takes its total. - Fourth, forgetting the
-rflag. The symptom is output wrapped in quotes, like"Sana"instead ofSana, which breaks the next command in a pipe. The fix is to add-rfor raw output whenever the result feeds another tool.
Frequently Asked Questions
Is jq the same as jQuery? No. jQuery is a JavaScript library for web pages, while jq is a command-line program for processing JSON. The two are unrelated apart from the name.
Do I need to install anything to try jq? On most systems, yes, but it is one small binary with no dependencies. On Ubuntu and Debian, sudo apt install jq is enough; on macOS, brew install jq.
Can jq edit a JSON file in place? No. jq reads input and prints a new document, so write the output to a temporary file and move it over the original: jq '.foo = 1' orders.json > tmp.json && mv tmp.json orders.json.
Why does group_by need sort_by first? Because group_by only groups neighbours that sit next to each other. Sorting by the same key first puts equal values together, so every order for one city lands in one group.
What does the -c flag do? It prints each result on one line, which suits logs and piping one JSON object per line into another tool.
What to remember
jqis a command-line JSON processor, not jQuery, and it never edits a file in place.- Filters pipe with
|, andselectkeeps only the objects that match a condition. - A string where a number belongs breaks
add, andtonumberfixes it before the sum. group_byneedssort_byon the same key first, or groups split apart.- Missing keys return
nullsilently, so use//to set a default. - The
-rflag prints plain text without quotes, which keeps pipes working.
Where this leaves you
jq pays for itself the first time an API hands you five hundred lines and you need one number. The demo proved the shape of it: one file, five real orders, a filter that listed the Karachi customers, a sum that failed honestly on a string total, and a one-word fix that gave the real grand total of Rs 45,350.
Open the last API response you saved, run jq 'length' on it, then ask it one real question about your own data. A tool that answers in one line beats a script you have to write and save.
Further reading
- jq manual
- jq on GitHub
- Elysia Bun Tutorial: Build a Real Orders API for Shops
- Koa Tutorial: Build a Node.js Orders API From Scratch
- FastAPI Explained: Python APIs at Full Speed
- Postman Explained: Testing APIs Before the Frontend Exists
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Comments
No comments yet. Start the discussion.