toJson

import { toJson } from "jsr:@ende/streams";

function

function toJson(stream: ReadableStream<string> | ReadableStream<Uint8Array>): Promise<unknown>

Converts a https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON-formatted ReadableSteam of strings or Uint8Arrays to an object. Works the same as Response.json and Request.json, but also extends to support streams of strings.

stream: ReadableStream<string> | ReadableStream<Uint8Array>

A ReadableStream whose chunks compose a JSON.

Returns

A promise that resolves to the parsed JSON.

Example: Usage with a stream of strings

import { toJson } from "@ende/streams/to-json";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([
  "[1, true",
  ', [], {}, "hello',
  '", null]',
]);
assertEquals(await toJson(stream), [1, true, [], {}, "hello", null]);

Example: Usage with a stream of Uint8Arrays

import { toJson } from "@ende/streams/to-json";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([
  "[1, true",
  ', [], {}, "hello',
  '", null]',
]).pipeThrough(new TextEncoderStream());
assertEquals(await toJson(stream), [1, true, [], {}, "hello", null]);

Source