Skip to the content
GigaJSON
All tools
Format and check
View and query
Convert
JSON to code
Encode and decode
Sample files
Guides Open GigaJSON

jq with JSON Lines: filter, count, join and reshape JSONL files

· 5 min read · By Amir Badi

jq and JSON Lines fit together without any setup: jq reads one JSON value after another, and a .jsonl file is exactly that. The part that trips people up is the moment a question needs more than one line at a time (a count, a total, the first match, a duplicate), because that's when -s, -n and inputs come in. This guide explains those three, then gives recipes I use on event exports and datasets.

Every command was run with jq 1.7 on this events.jsonl (record 2 appears twice on purpose):

{"id":1,"ts":"2026-11-20T09:12:04Z","user":7,"type":"view","path":"/pricing"}
{"id":2,"ts":"2026-11-20T09:13:40Z","user":7,"type":"purchase","amount":49,"payload":"{\"plan\":\"pro\",\"seats\":3}"}
{"id":3,"ts":"2026-11-20T10:01:15Z","user":9,"type":"view","path":"/docs"}
{"id":2,"ts":"2026-11-20T09:13:40Z","user":7,"type":"purchase","amount":49,"payload":"{\"plan\":\"pro\",\"seats\":3}"}
{"id":4,"ts":"2026-11-21T08:30:00Z","user":9,"type":"purchase","amount":19,"payload":"{\"plan\":\"basic\",\"seats\":1}"}

For logs in particular (levels, status codes, broken lines, tail -f), How to view and query API responses and NDJSON logs has its own recipes.

How jq reads a JSONL file

By default jq runs the filter once per line. Each line is ., and each result is printed:

jq -c 'select(.type == "purchase") | {id, user, amount}' events.jsonl
{"id":2,"user":7,"amount":49}
{"id":2,"user":7,"amount":49}
{"id":4,"user":9,"amount":19}

Always add -c when the output is JSON Lines again. Without it, jq pretty-prints each record over several lines, and the file it writes is no longer JSON Lines.

A filter that runs once per line can't count or compare lines. For that there are two ways to see the whole file:

Option What . is Memory Use it for
-s (slurp) one array of every line the whole file sorting, grouping, unique_by, anything that needs all records at once
-n with inputs null; inputs yields the lines one by one one line at a time (plus what you keep) counting, totals, the first match, stopping early
jq -s 'length' events.jsonl                                           # 5
jq -n '[inputs | select(.type == "purchase")] | length' events.jsonl  # 3

Forget -n and the result is quietly wrong: jq '[inputs] | length' events.jsonl prints 4, not 5, because jq read the first line as . before inputs got the rest.

Count, total and group

jq -n 'reduce inputs as $e (0; . + ($e.amount // 0))' events.jsonl     # 117
jq -nc 'reduce inputs as $e ({}; .[$e.type] += 1)' events.jsonl          # {"view":2,"purchase":3}
jq -nc '[inputs.user] | unique' events.jsonl                             # [7,9]

reduce keeps only the running total, so it works on files far bigger than memory. // 0 treats a missing amount as zero instead of failing on null. The total counts record 2 twice, which is the next problem.

First matches and samples

jq -nc 'first(inputs | select(.user == 9))' events.jsonl    # stops reading after the match
jq -nc 'limit(2; inputs)' events.jsonl                      # the first two records

first and limit stop jq as soon as they have what they need, which matters on a multi-gigabyte export. For a quick look, head -n 100 events.jsonl | jq . does the same from the shell.

Remove duplicates

With slurp, unique_by keeps one record per id, sorted by that id:

jq -sc 'unique_by(.id)[] | .id' events.jsonl     # 1 2 3 4

To keep the file order and avoid loading every record, remember only the ids you've seen:

jq -nc 'foreach inputs as $e ({}; .[$e.id | tostring] += 1; select(.[$e.id | tostring] == 1) | $e)' events.jsonl

This writes records 1, 2, 3 and 4 in their original order, each once. Memory grows with the number of distinct ids, not the size of the records.

Sort and filter by time

jq -sc 'sort_by(.ts) | reverse | .[0]' events.jsonl          # the latest record
jq -c 'select(.ts >= "2026-11-21")' events.jsonl              # records from 21 November on

ISO 8601 timestamps in the same format and time zone sort correctly as text, so a plain string comparison filters by date. If yours mix formats or offsets, convert them first with fromdateiso8601 (which wants 2026-11-21T08:30:00Z exactly) or compare numbers.

Reshape every line

jq -c 'del(.payload) | .source = "web"' events.jsonl > clean.jsonl
jq -c '{id, ts, user}' events.jsonl > slim.jsonl

Each record goes through the filter and comes out on its own line, so a reshaped file is still JSON Lines. Never redirect to the file you're reading: > events.jsonl empties it before jq starts.

JSON inside a string field

Event pipelines often store a nested object as an escaped string, like payload here. fromjson parses it:

jq -c 'select(.payload) | .payload |= fromjson | {id, payload}' events.jsonl
{"id":2,"payload":{"plan":"pro","seats":3}}
{"id":2,"payload":{"plan":"pro","seats":3}}
{"id":4,"payload":{"plan":"basic","seats":1}}

.payload // empty | fromjson | .plan pulls a single field out of it. tojson does the reverse, turning an object back into an escaped string. Unescape JSON explains how a string gets escaped twice and how to undo it in other languages.

Join with a second file

To add each user's country from users.jsonl ({"id":7,"name":"Ana","country":"PE"} and so on), load the small file whole with --slurpfile, index it by id, and stream the big one:

jq -c --slurpfile users users.jsonl \
  '($users | INDEX(.id)) as $u | . + {country: $u[.user | tostring].country} | {id, user, country}' events.jsonl
{"id":1,"user":7,"country":"PE"}
{"id":2,"user":7,"country":"PE"}
{"id":3,"user":9,"country":"NO"}

INDEX turns the array into an object keyed by id. Its keys are strings, hence .user | tostring. Keep the lookup file small; the events file can be any size.

Several files, compressed files, CSV

jq -r '"\(input_filename): \(.id)"' events.jsonl users.jsonl   # which file each record came from
zcat events.jsonl.gz | jq -c 'select(.amount > 20) | .id'        # gzip, no need to unpack first
jq -r '[.id, .ts, .user, .type, (.amount // "")] | @csv' events.jsonl > events.csv

jq reads several files as one stream, in order. For CSV, @csv quotes text and leaves numbers bare. Convert JSON to CSV covers nested fields and Excel.

When jq stops at a bad line

One line that isn't valid JSON ends the run with parse error … at line N, and every line after it is skipped. Read the lines as raw text and parse them yourself to skip bad ones: jq -cR 'fromjson? // empty'. Convert JSON to JSON Lines and back shows how to find every bad line with its number before you decide to drop them.

Without a terminal

The JSON Lines Viewer opens .jsonl and .ndjson files of up to 1 GB in the browser as a table with one row per line, plus a tree and a query panel; nothing is uploaded. There the lines are one list, so a jq query starts with .[]: .[] | select(.type == "purchase"). jq runs there on files up to 20 MB; past that, use JSONPath or JMESPath in the same panel. The jq Playground is the place to work a filter out on a sample before you run it on the whole file.

Questions

Does jq work with JSONL files?

Yes, without any option. jq reads one JSON value after another, so it runs your filter once per line of a JSON Lines file. Add -c to write each result on one line, which keeps the output valid JSON Lines.

What is the difference between jq -s and jq -n with inputs?

-s (slurp) reads every line into one array before running the filter, so the whole file is in memory. -n with inputs starts with no input and lets the filter pull the lines one by one, so reduce and first can count or stop early without holding the file. Without -n, inputs skips the first line, because jq has already read it as .

How do I count lines that match in a JSONL file with jq?

jq -n '[inputs | select(.type == "purchase")] | length' events.jsonl. To count every value of a field at once: jq -nc 'reduce inputs as $e ({}; .[$e.type] += 1)' events.jsonl, which gives {"view":2,"purchase":3}.

How do I unescape a JSON string field with jq?

Use fromjson on the field: jq -c '.payload |= fromjson' events.jsonl turns "{\"plan\":\"pro\"}" into {"plan":"pro"}. tojson does the reverse.

How do I convert JSONL to JSON with jq?

jq -s '.' file.jsonl > file.json collects the lines into one array. The reverse is jq -c '.[]' file.json > file.jsonl.

More from the blog