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 stream
const stream = createJsonStream();
// Subscribe to updates
const unsubscribe = stream.subscribe(json => {
console.log('Updated JSON:', json);
});
// Push chunks as they arrive
stream.pushChunk('{"mess');
stream.pushChunk('age": "Hello');
stream.pushChunk(', world!"}');
// Unsubscribe when done
unsubscribe();import React from 'react';
import { createJsonStream, useJsonStream } from 'json-streaming';
const MyComponent = () => {
// Create a stream (typically you would do this outside the component or in a provider)
const stream = React.useMemo(() => createJsonStream(), []);
// Get the current JSON state
const data = useJsonStream(stream);
// Example: pushing a chunk when a button is clicked
const pushChunk = () => {
stream.pushChunk('{"message": "Hello, world!"}');
};
return (
<div>
<button onClick={pushChunk}>Push JSON Chunk</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};import { createStreamFromReadable } from 'json-streaming';
// Assuming your API endpoint streams JSON
fetch('/api/stream-endpoint')
.then(response => {
if (!response.body) {
throw new Error('No response body');
}
// Create a stream from the response
const jsonStream = createStreamFromReadable(response.body);
// Subscribe to updates
jsonStream.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