JSON 21 ๐ Streaming High-Volume JSON Parsing (oboe, bfj)
The JSON.parse function materializes the entire document in memory before it returns a single value. For a file under ten megabytes, the materialization is invisible. For a file over one hundred megabytes, the materialization is the problem: the text is held in memory, the resulting object tree is held alongside it, and the V8 heap grows to several times the file size. The streaming parsers are the answer. They read the input as a byte stream, emit the events as the structure becomes available, and never hold more than a record or a chunk in memory at a time . The two libraries that the chapter coversโoboe and bfjโare the browser-oriented and the Node.js-oriented implementations of that model, and the choice between them is the choice of the environment and the ergonomics.
The oboe library is the selector-based parser. It was built for the case where the HTTP response is large and the application wants to render the results progressively instead of waiting for the whole body . The .node() and the .path() methods register the JSONPath-like patterns, and the callback fires when the matching node is found in the stream. The bfj library is the Node.js-oriented parser with the SAX-style event emitter. The bfj.walk() returns an event emitter, and the events are the array, the object, the property, the string, the number, the literal, the endArray, the endObject, and the end . The two libraries solve the same problem with the different ergonomics, and the choice is the environment and the programming style.
Key point: oboe is the selector-based streaming parser for the browser and the Node.js, and it fires the callbacks when the matching nodes are found. bfj is the SAX-style event emitter for the Node.js, and it fires the events as the tokens are encountered. The two are the streaming parsers that keep the memory flat, and the choice is the selector ergonomics against the event ergonomics.
Why the streaming parsers exist
The memory problem. The JSON.parse reads the whole text, tokenizes it, and builds the whole object tree. The peak memory is the text size plus the object tree size plus the V8 overhead, and the benchmark of a 136 MB GeoJSON file measured the JSON.parse at the 503 MB peak . The streaming parser reads the chunks, parses the structure incrementally, and hands the individual records to the caller. The memory is flat regardless of the input size, and the flat memory is the reason the streaming parser handles the multi-gigabyte files that the JSON.parse cannot .
The latency problem. The JSON.parse gives nothing until the whole body has arrived. The streaming parser gives the first record as soon as the first record has arrived, and the progressive output is the mechanism that makes the first results visible before the last byte has downloaded . The oboe library was built for the progressive rendering of the HTTP responses, and the progressive rendering is the reason the old Google Maps search showed the results before the body finished downloading .
The selector problem. The streaming parser has to decide which parts of the stream the application cares about. The oboe uses the JSONPath-like selectors: the .node('users.*', callback) fires the callback for each user, and the callback receives the node, the path, and the ancestors . The bfj uses the SAX-style events: the caller subscribes to the property and the string events and reconstructs the structure itself. The selector is the higher-level abstraction, and the events are the lower-level abstraction.
The trade-off. The streaming parser is slower than the JSON.parse for the whole document. The oboe documentation states that the oboe requires more CPU time than the JSON.parse, and the benchmark of the oboe on a large file measured the 7,263 ms against the 858 ms of the JSON.parse . The slower total time is the price of the flat memory, and the price is the reason the streaming parser is the choice for the large files, not the small ones.
a. The oboe library and the selector-based parsing
The oboe function is the single entry point. It accepts the URL string, the options object, or the readable stream. The .node() registers the callback for the matching node, and the callback receives the node, the path, and the ancestors.
// The basic oboe usage
import oboe from "oboe";
oboe("/api/users")
.node("users.*", (user, path, ancestors) => {
// The callback fires for each user as soon as it is fully received.
// The user is the complete object.
appendToTable(user);
})
.done((full) => {
// The done event fires when the response is complete.
console.log(`got ${full.users.length} users`);
});
The .node("users.*", callback) is the selector that matches each element of the users array. The callback fires as soon as the element is complete, and the complete element is the mechanism that lets the application render the record before the next one has arrived . The .done() is the callback for the entire parsed JSON, and the entire JSON is the mechanism for the summary after the stream completes.
The .path() is the same as the .node() except that the callback fires as soon as the path is found, before the value at the path is known. The path is the mechanism that lets the application start the interface before the content is complete .
// The path event
oboe("/api/data")
.path("items", (value, path, ancestors) => {
// The callback fires when the "items" key is found.
// The value is not yet available.
showLoadingSpinner();
})
.node("items.*", (item) => {
// The callback fires for each item.
appendItem(item);
});
The .path() is the mechanism that separates the “the data is coming” from the “the data is here”. The two events are the mechanism that makes the progressive rendering possible, and the progressive rendering is the reason the oboe exists.
The oboe accepts the readable stream in the Node.js. The stream is the mechanism that lets the application use the custom source, and the custom source is the reason the oboe is not limited to the HTTP.
// The readable stream
import fs from "node:fs";
import oboe from "oboe";
oboe(fs.createReadStream("large.json"))
.node("records.*", (record) => {
// The callback fires for each record.
processRecord(record);
});
The oboe(fs.createReadStream("large.json")) is the mechanism that reads the file as the stream. The stream is the reason the oboe can process the local files as well as the HTTP responses.
b. The bfj library and the SAX-style parsing
The bfj.walk() returns an event emitter, and the caller subscribes to the events. The events are defined as the public properties of the bfj.events object.
// The basic bfj.walk usage
import bfj from "bfj";
import fs from "node:fs";
const emitter = bfj.walk(fs.createReadStream("large.json"));
emitter.on(bfj.events.array, () => { /* an array started */ });
emitter.on(bfj.events.object, () => { /* an object started */ });
emitter.on(bfj.events.property, (name) => { /* a property name */ });
emitter.on(bfj.events.string, (value) => { /* a string value */ });
emitter.on(bfj.events.number, (value) => { /* a number value */ });
emitter.on(bfj.events.literal, (value) => { /* true, false, or null */ });
emitter.on(bfj.events.endArray, () => { /* an array ended */ });
emitter.on(bfj.events.endObject, () => { /* an object ended */ });
emitter.on(bfj.events.end, () => { /* the stream ended */ });
The bfj.events.property is the event that carries the property name, and the next event is the property’s value . The sequence of the events is the mechanism that lets the caller reconstruct the structure, and the reconstruction is the reason the bfj is the lower-level API.
The bfj.walk() is the parser that emits the events. The bfj.match() is the selector-based alternative, and the bfj.parse() is the whole-document parser that returns the promise.
// The bfj.match selector
import bfj from "bfj";
import fs from "node:fs";
const emitter = bfj.match(fs.createReadStream("large.json"), "records.*");
emitter.on("data", (record) => {
// The callback fires for each matching record.
processRecord(record);
});
emitter.on("end", () => {
// The stream ended.
});
The bfj.match(stream, selector) is the mechanism that fires the data event for each matching record. The selector is the simpler API than the event subscription, and the simplicity is the reason the bfj.match exists.
The bfj has the yieldRate option, and the option is the mechanism that controls how often the parser yields to the event loop . The default is 1024, and the smaller value yields more often (the less blocking per tick but the slower total), and the larger value yields less often (the more blocking per tick but the faster total). The yieldRate is the mechanism that lets the application tune the responsiveness against the throughput.
// The yieldRate option
const emitter = bfj.walk(fs.createReadStream("large.json"), {
yieldRate: 512, // Yield to the event loop every 512 items
});
The yieldRate: 512 is the mechanism that keeps the event loop responsive. The parser processes the 512 items, yields to the event loop, and resumes. The yielding is the reason the bfj does not block the Node.js process for the entire parse.
Complete Example Session
// ============================================
// PART 1: THE OBOE NODE SELECTOR
// ============================================
import oboe from "oboe";
oboe("/api/users")
.node("users.*", (user) => {
// The callback fires for each user.
appendToTable(user);
})
.done((full) => {
// The done event fires when the response is complete.
console.log(`got ${full.users.length} users`);
});
// ============================================
// PART 2: THE OBOE PATH EVENT
// ============================================
oboe("/api/data")
.path("items", () => showLoadingSpinner())
.node("items.*", (item) => appendItem(item));
// The path fires before the node.
// ============================================
// PART 3: THE OBOE STREAM
// ============================================
import fs from "node:fs";
oboe(fs.createReadStream("large.json"))
.node("records.*", (record) => processRecord(record));
// The stream is the custom source.
// ============================================
// PART 4: THE BFJ WALK EVENTS
// ============================================
import bfj from "bfj";
const emitter = bfj.walk(fs.createReadStream("large.json"));
emitter.on(bfj.events.property, (name) => console.log(name));
emitter.on(bfj.events.string, (value) => console.log(value));
emitter.on(bfj.events.end, () => console.log("done"));
// The events fire as the tokens are encountered.
// ============================================
// PART 5: THE BFJ MATCH SELECTOR
// ============================================
const matchEmitter = bfj.match(fs.createReadStream("large.json"), "records.*");
matchEmitter.on("data", (record) => processRecord(record));
// The match fires the data event for each matching record.
// ============================================
// PART 6: THE YIELD RATE
// ============================================
const tunedEmitter = bfj.walk(fs.createReadStream("large.json"), {
yieldRate: 512, // Yield to the event loop every 512 items
});
// The smaller value yields more often.
// ============================================
// PART 7: THE PAUSE AND RESUME
// ============================================
const pauseEmitter = bfj.walk(fs.createReadStream("large.json"));
const resume = pauseEmitter.pause();
// Later, when ready to continue:
resume();
// The pause prevents the further events.
// ============================================
// PART 8: THE ERROR HANDLING
// ============================================
emitter.on(bfj.events.dataError, (error) => {
// The error has the lineNumber and the columnNumber.
console.error(error.lineNumber, error.columnNumber);
});
// The dataError is the syntax error in the stream.
// ============================================
// PART 9: THE NDJSON
// ============================================
const ndjsonEmitter = bfj.walk(fs.createReadStream("data.ndjson"), {
ndjson: true,
});
ndjsonEmitter.on(bfj.events.endLine, () => {
// The endLine fires between the NDJSON chunks.
});
// The ndjson option treats the newlines as the delimiters.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The oboe is the selector-based parser.
// [ ] The bfj is the SAX-style event emitter.
// [ ] The oboe fires the callbacks for the matching nodes.
// [ ] The bfj fires the events for the tokens.
// [ ] The yieldRate controls the event loop yielding.
// [ ] The pause and the resume control the processing.
The ten parts covered the oboe node selector, the oboe path event, the oboe stream, the bfj walk events, the bfj match selector, the yield rate, the pause and resume, the error handling, the NDJSON, and the checklist. The through-line is that the two libraries are the streaming parsers with the different ergonomics.
Quick Reference
The library comparison
| Aspect | oboe | bfj |
|---|---|---|
| The style | The selector-based | The SAX-style events |
| The environment | The browser and the Node.js | The Node.js |
| The event API | .node(), .path(), .done() | bfj.walk(), bfj.match() |
| The error event | The .fail() | bfj.events.dataError |
| The stream | The HTTP and the readable stream | The readable stream |
The oboe events
| Method | Purpose |
|---|---|
.node(pattern, cb) | The callback for the matching node |
.path(pattern, cb) | The callback for the matching path |
.done(cb) | The callback for the complete JSON |
.start(cb) | The callback for the response start |
.fail(cb) | The callback for the error |
The bfj events
| Event | Purpose |
|---|---|
bfj.events.array | The array start |
bfj.events.object | The object start |
bfj.events.property | The property name |
bfj.events.string | The string value |
bfj.events.number | The number value |
bfj.events.literal | The true, false, or null |
bfj.events.end | The stream end |
bfj.events.dataError | The syntax error |
The bfj options
| Option | Default | Purpose |
|---|---|---|
yieldRate | 1024 | The items per event loop tick |
ndjson | false | The newline-delimited JSON |
stringChunkSize | โ | The string chunking |
Best Practices
โ Do This:
// Use the oboe for the progressive rendering
oboe("/api/users").node("users.*", renderUser); // โ
// Use the bfj for the Node.js pipeline
bfj.match(stream, "records.*").on("data", processRecord); // โ
// Use the yieldRate for the responsiveness
bfj.walk(stream, { yieldRate: 512 }); // โ
โ Don’t Do This:
// Use the JSON.parse for the large file
JSON.parse(fs.readFileSync("large.json")); // the memory blowup // โ
// Use the oboe for the small file
// The oboe is slower than the JSON.parse for the small data. // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The memory grows with the file | The JSON.parse is used | Use the streaming parser |
| The oboe is slow | The file is small | Use the JSON.parse |
| The bfj blocks the event loop | The yieldRate is too large | Decrease the value |
| The NDJSON is not parsed | The ndjson option is missing | Set the option to true |
Real-World Examples
1. The oboe node selector
oboe("/api/users").node("users.*", renderUser);
2. The oboe path event
oboe("/api/data").path("items", showSpinner);
3. The oboe stream
oboe(fs.createReadStream("large.json")).node("records.*", process);
4. The bfj walk
bfj.walk(stream).on(bfj.events.string, logString);
5. The bfj match
bfj.match(stream, "records.*").on("data", process);
6. The yield rate
bfj.walk(stream, { yieldRate: 512 });
7. The pause
const resume = emitter.pause();
8. The data error
emitter.on(bfj.events.dataError, (e) => console.error(e.lineNumber));
9. The NDJSON
bfj.walk(stream, { ndjson: true });
10. The done
oboe("/api").done((full) => console.log(full));
Visual
The Streaming Model
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE STREAMING MODEL โ
โ โ
โ The byte stream โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The parser โ The state machine โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The events โ The record or the token โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The callback โ The application code โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The oboe Selector
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE OBOE SELECTOR โ
โ โ
โ The JSON stream โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The "users.*" โ The selector โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The callback fires โ The user object โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The bfj Events
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE BFJ EVENTS โ
โ โ
โ The JSON stream โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ bfj.walk() โ The event emitter โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโผโโโโโโโฌโโโโโโโโโโโ โ
โ โผ โผ โผ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โarray โโobjectโโstringโโend โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| The problem | The JSON.parse materializes the whole document |
| The solution | The streaming parsers |
oboe | The selector-based parser for the browser and the Node.js |
bfj | The SAX-style event emitter for the Node.js |
| The oboe API | The .node(), the .path(), the .done() |
| The bfj API | The bfj.walk(), the bfj.match() |
| The bfj options | The yieldRate, the ndjson |
Key takeaways:
- The streaming parsers keep the memory flat. The
JSON.parsematerializes the whole document, and the peak memory is the text plus the object tree plus the V8 overhead. The streaming parser reads the chunks, emits the records, and never holds more than a record at a time . The flat memory is the reason the streaming parser handles the multi-gigabyte files. oboeis the selector-based parser. The.node()and the.path()register the JSONPath-like patterns, and the callback fires when the matching node is found. The progressive rendering is the reason theoboeexists, and the browser is the environment it was built for .bfjis the SAX-style event emitter. Thebfj.walk()fires thearray, theobject, theproperty, thestring, thenumber, theliteral, and theendevents, and the caller reconstructs the structure. Thebfj.match()is the selector-based alternative, and theyieldRateis the responsiveness control .- The streaming parser is slower than the
JSON.parsefor the small files. The oboe benchmark measured the 7,263 ms against the 858 ms of theJSON.parse. The slower total is the price of the flat memory, and the price is the reason the streaming parser is the choice for the large files. - The choice is the environment and the ergonomics. The
oboeis the browser-oriented selector-based parser, and thebfjis the Node.js-oriented SAX parser. The two solve the same problem, and the choice is the programming style and the environment.
Remember: The streaming JSON parsing is the answer to the memory problem. The oboe is the selector-based parser, and the bfj is the SAX-style event emitter. The two keep the memory flat, and the flat memory is the reason they handle the files that the JSON.parse cannot. The choice is the environment and the ergonomics.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!