@yukiakai/json-stream-parser
v1.0.1
Published
Streaming JSON parser that handles fragmented data and emits full JSON objects when complete.
Maintainers
Readme
@yukiakai/json-stream-parser
A lightweight and zero-dependency streaming JSON parser for Node.js and browsers.
It handles fragmented JSON input — such as from sockets, WebSockets, or chunked streams — and emits complete JSON values when they are fully parsed.
✨ Features
- 📦 Parses streamed JSON incrementally (like from
.write()chunks) - ⚡ Emits complete JSON values when available
- 🔍 Detects incomplete vs. invalid JSON properly
- 🧠 Skips strings
"..."correctly to avoid false{or}detection - 🛠 Tiny and dependency-free
📦 Installation
npm install @yukiakai/json-stream-parser🚀 Usage
import { JsonStreamParser } from '@yukiakai/json-stream-parser';
const parser = new JsonStreamParser();
parser.on('data', (jsonValue) => {
console.log('Parsed:', jsonValue);
});
parser.on('error', (err) => {
console.error('Invalid JSON:', err.message);
});
// Simulate fragmented incoming JSON
parser.write('{"id":1,');
parser.write('"name":"Alice"}');
parser.write('\n{"id":2,"name":"B');
parser.write('ob"}');🧩 API
new JsonStreamParser()
Creates a new instance of the streaming parser.
parser.write(chunk: string | Buffer)
Feeds partial input into the parser. It automatically buffers and emits full JSON values when complete.
Events
data:(value: any)– Emitted when a full valid JSON value is parsed.error:(error: Error)– Emitted if an invalid JSON structure is detected (e.g. unclosed brace).
📚 Example: With Socket
import net from 'net';
import { JsonStreamParser } from '@yukiakai/json-stream-parser';
const server = net.createServer((socket) => {
const parser = new JsonStreamParser();
parser.on('data', (obj) => {
console.log('Received JSON:', obj);
});
parser.on('error', (err) => {
console.warn('Bad JSON:', err.message);
socket.destroy(); // or handle gracefully
});
socket.on('data', (chunk) => {
parser.write(chunk);
});
});
server.listen(3000);🧪 Tests
npm run test📄 License
MIT © Yuki Akai
