Skip to main content

@std/json@0.215.0

latest
Works with
It is unknown whether this package works with Browsers, Deno, Node.js, Cloudflare Workers, Bun
It is unknown whether this package works with Browsers
It is unknown whether this package works with Deno
It is unknown whether this package works with Node.js
It is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Bun
JSR Score70%
Published2 years ago (0.215.0)
class JsonStringifyStream
extends TransformStream<unknown, string>

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".

Examples

Example 1

import { JsonStringifyStream } from "@std/json/json_stringify_stream";

const file = await Deno.open("./tmp.jsonl", { create: true, write: true });

ReadableStream.from([{ foo: "bar" }, { baz: 100 }])
  .pipeThrough(new JsonStringifyStream()) // convert to JSON lines (ndjson)
  .pipeThrough(new TextEncoderStream()) // convert a string to a Uint8Array
  .pipeTo(file.writable)
  .then(() => console.log("write success"));

To convert to JSON Text Sequences, set the prefix to the delimiter "\x1E" as options.

import { JsonStringifyStream } from "@std/json/json_stringify_stream";

const file = await Deno.open("./tmp.jsonl", { create: true, write: true });

ReadableStream.from([{ foo: "bar" }, { baz: 100 }])
  .pipeThrough(new JsonStringifyStream({ prefix: "\x1E", suffix: "\n" })) // convert to JSON Text Sequences
  .pipeThrough(new TextEncoderStream())
  .pipeTo(file.writable)
  .then(() => console.log("write success"));

If you want to stream JSON lines from the server:

import { JsonStringifyStream } from "@std/json/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);
});

Constructors

new JsonStringifyStream(unnamed 0?: StringifyStreamOptions)

Constructs new instance.

Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@std/json

Import symbol

import { JsonStringifyStream } from "@std/json";
or

Import directly with a jsr specifier

import { JsonStringifyStream } from "jsr:@std/json";