Class JsonStringifyStream

Convert each chunk to JSON string.

This can be used to stringify JSON lines, NDJSON, JSON Text Sequences, and Concatenated JSON.

You can optionally specify a prefix and suffix for each chunk. The default prefix is "" and the default suffix is "\n".

import { JsonStringifyStream } from "@std/json/stringify-stream";
import { assertEquals } from "@std/assert";

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

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

Set options.prefix to \x1E to stringify JSON Text Sequences.

import { JsonStringifyStream } from "@std/json/stringify-stream";
import { assertEquals } from "@std/assert";

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

assertEquals(await Array.fromAsync(stream), [
`\x1E{"foo":"bar"}\n`,
`\x1E{"baz":100}\n`
]);
import { JsonStringifyStream } from "@std/json/stringify-stream";

// A server that streams one line of JSON every second
Deno.serve(() => {
let intervalId: number | undefined;
const readable = new ReadableStream({
start(controller) {
// Enqueue data once per second
intervalId = setInterval(() => {
controller.enqueue({ now: new Date() });
}, 1000);
},
cancel() {
clearInterval(intervalId);
},
});

const body = readable
.pipeThrough(new JsonStringifyStream()) // Convert data to JSON lines
.pipeThrough(new TextEncoderStream()); // Convert a string to a Uint8Array

return new Response(body);
});
Hierarchy
  • TransformStream<unknown, string>
    • JsonStringifyStream

Constructors

Properties

Constructors

Properties

readable: ReadableStream<string>
writable: WritableStream<unknown>