A JavaScript/TypeScript library for incrementally processing streamed JSON data from LLM outputs and binding it to UI components.
- 🔄 Incremental JSON parsing from text streams
- 🧩 Progressive JSON state construction as data arrives
- 🔌 React hooks for easy integration
- 📜 Framework-agnostic core library
- 🚀 Lightweight with no external dependencies
npm install json-streamingimport{createJsonStream}from'json-streaming';// Create a new streamconststream=createJsonStream();// Subscribe to updatesconstunsubscribe=stream.subscribe(json=>{console.log('Updated JSON:',json);});// Push chunks as they arrivestream.pushChunk('{"mess');stream.pushChunk('age": "Hello');stream.pushChunk(', world!"}');// Unsubscribe when doneunsubscribe();importReactfrom'react';import{createJsonStream,useJsonStream}from'json-streaming';constMyComponent=()=>{// Create a stream (typically you would do this outside the component or in a provider)conststream=React.useMemo(()=>createJsonStream(),[]);// Get the current JSON stateconstdata=useJsonStream(stream);// Example: pushing a chunk when a button is clickedconstpushChunk=()=>{stream.pushChunk('{"message": "Hello, world!"}');};return(<div><buttononClick={pushChunk}>Push JSON Chunk</button><pre>{JSON.stringify(data,null,2)}</pre></div>);};import{createStreamFromReadable}from'json-streaming';// Assuming your API endpoint streams JSONfetch('/api/stream-endpoint').then(response=>{if(!response.body){thrownewError('No response body');}// Create a stream from the responseconstjsonStream=createStreamFromReadable(response.body);// Subscribe to updatesjsonStream.subscribe(json=>{console.log('Updated JSON:',json);});});Creates a new JSON stream instance.
Options:
initialState: Initial JSON state (default:{})emitAllUpdates: Whether to emit updates even when the state hasn't changed (default:false)
Main class for handling JSON streams.
Methods:
pushChunk(chunk: string): Add a chunk of text to the streamsubscribe(callback): Subscribe to JSON state updatesgetCurrentJson(): Get the current JSON stateonStatusChange(callback): Subscribe to status changesonError(callback): Subscribe to errorscomplete(): Signal that the stream is completereset(): Reset the stream to its initial state
Hook for using a JSON stream in React components.
Options:
paused: Whether to pause updates from the stream (default:false)selector: Function to extract a specific part of the JSON (default:undefined)
Hook for monitoring the status of a JSON stream.
MIT