Clarinet

0.12.6 · active · verified Tue Apr 21

Clarinet is a SAX-like streaming JSON parser for JavaScript, designed for efficient processing of JSON data in both browser and Node.js environments. Inspired by `sax-js` and `yajl`, it provides an evented API that allows developers to process JSON incrementally without needing to load the entire document into memory. This makes it particularly suitable for tasks such as indexing large JSON files or handling continuous streams of JSON where a full DOM-like object model is unnecessary. The package is currently at version 0.12.6, with recent releases (v0.12.x) focusing on minor bug fixes, performance optimizations, and dependency updates, indicating a maintenance cadence rather than rapid feature development. Its key differentiators include portability, robust error reporting with context (line/column numbers), the ability to parse JSON data off a stream incrementally, and a lightweight, simple-to-use API. It explicitly clarifies that it is not a direct replacement for `JSON.parse` but rather a tool for event-driven JSON consumption.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic event-driven parsing of a JSON string, showing how to handle object, array, key, and value events, as well as errors and stream completion for incremental processing.

const clarinet = require("clarinet");
const parser = clarinet.parser();

parser.onerror = function (e) {
  console.error("Parsing error: ", e.message, "at line:", parser.line, "column:", parser.column);
  // Optional: clear the error and resume parsing if recoverable
  this._parser.error = null; // Private, use with caution
  this._parser.resume(); // Private, use with caution
};
parser.onvalue = function (v) {
  console.log("Value:", v);
};
parser.onopenobject = function (key) {
  console.log("Open Object, first key:", key);
};
parser.onkey = function (key) {
  console.log("Key:", key);
};
parser.oncloseobject = function () {
  console.log("Close Object");
};
parser.onopenarray = function () {
  console.log("Open Array");
};
parser.onclosearray = function () {
  console.log("Close Array");
};
parser.onend = function () {
  console.log("Parser stream ended.");
};

parser.write('{"id":123, "name":"test", "data": [true, null, 42]}').close();
// Example with partial writes
// parser.write('{"foo": "bar"').write(',"baz": "qux"}').close();

view raw JSON →