json-stream-handler
v0.1.0
Published
Streaming JSON parser with path-based triggers for progressive object extraction
Maintainers
Readme
json-stream-handler
Streaming JSON parser with path-based triggers for progressive object extraction.
Motivation
LLM streaming outputs often embed JSON in markdown or natural language. Parsing the entire response before acting wastes time. json-stream-handler lets you define path-based triggers that fire as soon as matching values are parsed — no waiting for the full JSON.
Installation
npm install json-stream-handlerQuick Start
import { useJsonStream } from "json-stream-handler";
const parser = useJsonStream([
{
trigger: "products",
onArrayItem: (item, index) => console.log(`Product ${index}:`, item),
onObject: (arr) => console.log("All products:", arr),
},
{
trigger: "user.name",
onValue: (name) => console.log("User name:", name),
},
{
trigger: "*",
onObject: (root) => console.log("Root object:", root),
},
]);
parser.feed('{"products": [{"id": "P001", "name": "Widget"}');
parser.feed(', {"id": "P002", "name": "Gadget"}], "user": {"name":');
parser.feed('"Alice"}}');API
useJsonStream(triggers)
Returns { feed, reset, getBuffer, getJson }.
| Method | Description |
|--------|-------------|
| feed(chunk: string) | Feed raw text chunks. Parses incrementally, fires triggers on match. |
| reset() | Reset parser state for reuse. |
| getBuffer() | Get remaining unparsed buffer. |
| getJson() | Get the fully parsed JSON object (only after complete root). |
PathTrigger
| Property | Type | Description |
|----------|------|-------------|
| trigger | string | Dot-separated path, e.g. "products", "user.name", "*" for root. Array index syntax "items[0]" is supported. |
| onArrayItem | (item: any, index: number) => void | Fires for each element of a matched array. |
| onObject | (obj: any) => void | Fires when a matched object/array is fully parsed. |
| onValue | (value: any) => void | Fires when a matched scalar value (string, number, bool, null) is parsed. |
Special Trigger "*"
Matches the root-level JSON object or array. Fires exactly once. For root arrays, each element triggers onArrayItem.
Path Syntax
| Expression | Matches |
|------------|---------|
| "products" | Key products at any depth |
| "user.name" | Nested path user → name |
| "items[0]" | First element of items array |
| "*" | Root object or array |
Demo
npm run demoOpens a Svelte UI at http://localhost:5173 with 4 examples covering different trigger configurations.
Scripts
| Script | Description |
|--------|-------------|
| npm run build | Build ESM + CJS + types |
| npm run dev | Watch mode build |
| npm test | Run tests |
| npm run test:watch | Watch mode tests |
| npm run demo | Start demo UI |
License
MIT
