Skip to content

Guide

How to open huge JSON files without running out of memory

By Vishnu KumarPublished 5 min read

A 500 MB API export, a database dump, a log archive: double-click it and the editor freezes; load it in a script and the process dies. The cause is not the file size itself but how much memory a parsed JSON document takes. Here are real measurements, and the streaming techniques that avoid the problem entirely.

Why a 300 MB file needs gigabytes

Standard JSON parsers read the whole text and build the whole tree of objects in memory before you can touch the first value. Every object, string and number becomes a separate allocation with its own overhead. We generated a 37.3 MB file of 300,000 small user records and measured what parsing it costs:

Memory to parse a 37.3 MB JSON file (300,000 records)
ToolMemory usedRelative to file size
Python json.loadsabout 160 MB for the parsed objects4.3×
Node.js JSON.parseabout 70 MB of heap for the parsed objects, plus the 37 MB source string1.9× (plus the string)
jq '.items[]'368 MB peak resident memory, 1.1 s9.9×
jq --stream (shown below)3.6 MB peak resident memory, 16.8 s0.1×

Scale those ratios to a 1 GB file and Python needs over 4 GB of RAM for the parsed result, before your own code allocates anything. Text editors fare worse, because they also build line indexes, syntax highlighting and undo history over the whole file.

Node.js has a hard ceiling too: one string can hold at most buffer.constants.MAX_STRING_LENGTH characters, which is 536,870,888 on current 64-bit builds. fs.readFileSync(path, "utf8") on a larger file throws before JSON.parse ever runs.

First, look before you load

Often you only need to know what is in the file. These commands read a few kilobytes, not the whole thing:

# The first 2 KB: is it an object or an array? how is it indented?
head -c 2000 big.json

# Is it actually JSON Lines (one JSON value per line)?
head -n 3 big.json

# Size and line count
ls -lh big.json && wc -l big.json

If each line is a complete JSON value, the file is JSON Lines (often .jsonl or .ndjson), and you are in luck: every tool can process it one line at a time, using memory proportional to one record. jq -c 'select(.status == "error")' big.jsonl filters a file of any size.

Streaming with jq

For a single large document, jq's --stream mode emits the file as a sequence of [path, value] events instead of building the tree. fromstream reassembles complete values from those events, and truncate_stream strips leading path components so each array element is rebuilt on its own:

# Each element of the top-level array, one per line, in constant memory
jq -cn --stream 'fromstream(1 | truncate_stream(inputs))' big-array.json

# Each element of .items in {"items": [...], ...}
jq -cn --stream 'fromstream(2 | truncate_stream(inputs | select(.[0][0] == "items")))' big.json

# Pipe that into an ordinary jq filter to search or reshape
jq -cn --stream 'fromstream(2 | truncate_stream(inputs | select(.[0][0] == "items")))' big.json \
  | jq -c 'select(.active and .score > 90) | {id, email}'

The measurement above shows the trade-off: streaming kept memory at 3.6 MB instead of 368 MB, but took about fifteen times longer, because jq processes every leaf as a separate event. Use it when the file does not fit in memory, not by default. When it does fit, plain jq '.items[] | select(...)' is faster.

Converting a large array to JSON Lines once, with the first command above redirected to a file, is often the best move: every later query is a cheap line-by-line pass.

Streaming in Python with ijson

The ijson package parses incrementally and yields one complete item at a time, so memory stays proportional to the largest single record:

# pip install ijson
import ijson

with open("big.json", "rb") as f:
    # "items.item" means: each element of the array under the "items" key
    for user in ijson.items(f, "items.item"):
        if user["active"] and user["score"] > 90:
            print(user["id"], user["email"])

For a top-level array, the prefix is "item". ijson can use a C backend (yajl2_c) when it is available, which makes it several times faster than its pure-Python fallback; check ijson.backend to see which one you got. Numbers with a fractional part come back as Decimal by default, to avoid losing precision.

Streaming in Node.js

In Node, the stream-json package does the same job over a file stream:

// npm install stream-json
import { createReadStream } from "node:fs";
import { parser } from "stream-json";
import { pick } from "stream-json/filters/Pick.js";
import { streamArray } from "stream-json/streamers/StreamArray.js";

const pipeline = createReadStream("big.json")
  .pipe(parser())
  .pipe(pick({ filter: "items" }))  // descend into .items
  .pipe(streamArray());             // emit { key, value } per element

for await (const { value: user } of pipeline) {
  if (user.active && user.score > 90) console.log(user.id, user.email);
}

Other ecosystems have the same idea built in: Java's Jackson JsonParser and Go's json.Decoder with its Token method both read a document token by token.

When you need random access, not a scan

Streaming answers questions that one pass can answer: filtering, counting, converting. If you need to jump around the document repeatedly (look up record 250,000, then its neighbours, then a field deep inside it), load the data once into something built for queries:

  • SQLite or DuckDB: DuckDB can query a JSON file directly with SELECT * FROM read_json_auto('big.json'), and both turn repeated lookups into indexed queries.
  • A lazy viewer: a viewer that indexes the file's structure and materialises a node's children only when you expand it uses memory proportional to what is on screen, not to the file.

The second approach is how Jedi opens files of hundreds of megabytes on an Android phone: a streaming parser builds the tree lazily, so a node's children are created only when you expand it, and search runs against an index that grows as you type instead of blocking the screen.

Choosing an approach

Which technique fits which job
You want toUse
See the shape of the filehead -c, or a lazy viewer
Filter or extract records oncejq --stream, ijson or stream-json
Run many different queriesConvert to JSON Lines, or load into DuckDB or SQLite
Process a file that fits in RAM comfortablyPlain jq or your language's normal parser: it is faster
Produce big JSON yourselfWrite JSON Lines instead of one giant array, so consumers can stream it

The last row is the real fix. If you control the producer, emit one record per line. A JSON Lines file can be split, appended to, read in parallel, and processed in constant memory by every tool mentioned here.