JsonParseStream

import { JsonParseStream } from "jsr:@ende/json";

class

class JsonParseStream extends TransformStream<string, JsonValue>

Parse each chunk as JSON.

This can be used to parse JSON lines, NDJSON and JSON Text Sequences. Chunks consisting of spaces, tab characters, or newline characters will be ignored.

Example: Basic usage

import { JsonParseStream } from "@ende/json/parse-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([
  `{"foo":"bar"}\n`,
  `{"baz":100}\n`
]).pipeThrough(new JsonParseStream());

assertEquals(await Array.fromAsync(stream), [
  { foo: "bar" },
  { baz: 100 }
]);

Example: parse JSON lines or NDJSON from a file

import { TextLineStream } from "@ende/streams/text-line-stream";
import { JsonParseStream } from "@ende/json/parse-stream";
import { assertEquals } from "@ende/assert";

const file = await Ende.open("json/testdata/test.jsonl");

const readable = file.readable
  .pipeThrough(new TextDecoderStream())  // convert Uint8Array to string
  .pipeThrough(new TextLineStream()) // transform into a stream where each chunk is divided by a newline
  .pipeThrough(new JsonParseStream()); // parse each chunk as JSON

assertEquals(await Array.fromAsync(readable), [
 {"hello": "world"},
 ["👋", "👋", "👋"],
 {"deno": "🦕"},
]);

Constructors

constructor

new JsonParseStream()

Constructs new instance.

Source